블록

2012-02-27 2 views
0

에서있는 UIImage를 반환 나는 다음과 같은 코드를 가지고 :블록

- (UIImage *) getPublisherLogo 
{ 
    //check the cache if the logo already exists 
    NSString * imageUrl = [NSString stringWithFormat:@"%@/%@&image_type=icon", self.baseUrl, self.imageUrl_]; 


     ASIHTTPRequest * imageRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageUrl]]; 
     [imageRequest setTimeOutSeconds:30.0]; 
     [imageRequest setDownloadCache:[ASIDownloadCache sharedCache]]; 
     [imageRequest setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy]; 
     [imageRequest setCachePolicy:ASIAskServerIfModifiedWhenStaleCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy]; 
     [imageRequest setCompletionBlock:^(void){ 


      UIImage *img = [UIImage imageWithData:[imageRequest responseData] ]; 
      if (img){ 
       return img; 
      } 
     }]; 

     [imageRequest setFailedBlock:^(void){ 
      NSLog(@"Error in pulling image for publisher %@", [[imageRequest error] userInfo]); 
     }]; 

     [imageRequest startAsynchronous]; 
    } 
} 

문제는 반환 값이 /있는 UIImage가 블록에 돌려 주어집니다. 어떻게 이것을 피할 수 있습니까?

+0

메서드는 "publisherLogo"여야합니다. 그것은'get' 접두어를 가져서는 안됩니다. – bbum

답변

3

반환 블록이 void이기 때문에 완료 블록에서 아무 것도 반환 할 수 없습니다.

이미지가 설정 될 것으로 예상되는 객체에 setLogo:(UIImage *)image과 같은 새 메서드를 만들고 완료 블록 내에서 해당 메서드를 호출해야 할 수 있습니다.

+0

내 수업에서 속성으로 UIImage가 있고 블록이 반환되고 마침내이 UIImage를 반환하면 설정 한 것과 동일한 것입니까? – adit

+0

예. 실제로 속성의 이름이 'logo'인 경우 myObject.logo = img 또는 [myObject setLogo : img]를 호출 할 수 있습니다. 둘 다 똑같은 동작입니다. –

0

img 포인터를 블록 외부에 놓고 __BLOCK으로 선언하고이를 클로저로 사용할 수 있습니다. 그러나 img로 무엇을 할 계획인지 스스로에게 물어볼 필요가 있습니다. 호출이 비동기 적으로 이루어진다는 것을 명심하십시오. 블록에서 다른 메서드를 호출하고 채워진 이미지를 매개 변수로 전달해야한다고 생각합니다.

0

ASIHttpRequest 응답에서 객체를 가져 오는 경우 알림을 사용합니다. 당신의 완료 블록 사용자 정보에 사진과 함께

[[NSNotificationCenter defaultCenter] postNotificationName:@"getPhotoNotification" object:self userInfo:userInfo]; 

의 호출의 ViewController

- (void)viewDidLoad { 
    // Subscribe notifications 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onGetPhoto:) name:@"getPhotoNotification" object:nil]; 
} 

- (void)viewDidUnload { 
    [super viewDidUnload]; 
    // Unsubscribe from notifications 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"getPhotoNotification" object:nil]; 
} 

- (void)onGetPhoto:(NSNotification *)notification { 
    ... 
} 

예를 들어

.