2012-02-27 5 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'を持つべきではありません。私は私のクラスのプロパティとしてUIImageを持っているとするとき、ブロックに戻り、最終的には、このUIImageを返すように設定した場合 – bbum

答えて

3

あなたはそれがvoidを返されていますので、完了ブロックから何かを返すことができません。

画像が設定されると予想されるオブジェクトにsetLogo:(UIImage *)imageのような新しいメソッドを作成し、そのメソッドを補完ブロック内から呼び出す必要があります。

+0

は、それは同じことですか? – adit

+0

はい、そうです。プロパティが「ロゴ」と命名された場合には実際には、あなたが呼び出すことができますいずれかmyObject.logo = IMG、または[myObjectというsetLogo:IMG]。両方とも同じ動作です。 –

0

あなたはブロックの外側であなたのimgポインタを置いて、それを宣言__blockとクロージャとして使用することができます。しかし、実際にimgを使って何をするつもりであるのか、自分が非同期的に呼び出されることを念頭に置いて自分自身に尋ねる必要があります。ブロック内で別のメソッドを呼び出して、埋め込まれたイメージをパラメータとして渡す必要があると思います。

0

ASIHttpRequest応答からオブジェクトを取得するために、私は通知を使用。あなたの完了ブロックのUserInfoであなたの写真と

[[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 { 
    ... 
} 

で例えば

、。

関連する問題