J'ai le code suivant:
- (UIImage *) getPublisherLogo { //check the cache if the logo already exists NSSsortingng * imageUrl = [NSSsortingng ssortingngWithFormat:@"%@/%@&image_type=icon", self.baseUrl, self.imageUrl_]; ASIHTTPRequest * imageRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithSsortingng: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]; } }
Le problème est que la valeur de return / UIImage est returnnée à un bloc. Comment puis-je éviter cela?
Vous n'êtes pas en mesure de renvoyer quoi que ce soit à partir du bloc d'achèvement car il est returnné void
.
Vous aurez probablement besoin de créer une nouvelle méthode comme setLogo:(UIImage *)image
sur l'object qui attend l'image à définir, et appelez cette méthode à partir du bloc d'achèvement.
Vous pouvez placer votre pointeur img en dehors du bloc et le déclarer __BLOCK et l'utiliser comme une fermeture. Mais vous devez vraiment vous requestr ce que vous avez l'intention de faire avec img, en gardant à l'esprit que l'appel est fait de manière asynchronous. J'imagine que vous devriez faire un autre appel dans le bloc à une autre méthode et passer dans l'image peuplée en tant que paramètre.
Pour get un object de la réponse ASIHttpRequest, j'utilise des notifications.
Par exemple, dans le viewController appelant
- (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 { ... }
dans votre bloc d'achèvement
[[NSNotificationCenter defaultCenter] postNotificationName:@"getPhotoNotification" object:self userInfo:userInfo];
Avec votre photo dans userInfo.