如何从方法内的块返回变量? [英] How do I return a variable from a block inside a method?
问题描述
假设我有这个方法,给定一个URL返回一个UIImage:
Say I have this method that given a URL returns a UIImage:
- (void)getUIImageFromURL:(NSURL *)URL {
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *imageOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
imageOperation.responseSerializer = [AFImageResponseSerializer serializer];
[imageOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
return (UIImage *)responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[imageOperation start];
}
但它一直给我这个错误:
But it keeps giving me this error:
不兼容的块指针类型将'UIImage *(^)(AFHTTPRequestOperation * __ strong,_ strong id)'发送到'void(^)类型的参数(AFHTTPRequestOperation * _strong,__strong id)'
Incompatible block pointer types sending 'UIImage *(^)(AFHTTPRequestOperation *__strong, _strong id)' to parameter of type 'void (^)(AFHTTPRequestOperation *_strong, __strong id)'
我对块有些新意,所以也许我完全倒退了。我最好如何实现这样的方法?
I'm somewhat new to blocks, so perhaps I'm approaching this completely backwards. How best would I implement a method like this?
推荐答案
您无法从块内返回图像。这是一个异步API,不能以您尝试的方式使用。要么使用阻塞API,要么在下载映像之前阻塞该方法(一个糟糕的解决方案),要么实现对异步API的支持。例如,将完成块传递给 getImage
方法,并在下载操作的完成块中调用它。在此块中,使用图像执行所需操作。
You cannot return an image from inside a block. This is an asynchronous API and cannot be used in the manner you are attempting to. Either use a blocking API, where the method is blocking until the image is downloaded (a bad solution), or implement support for the asynchronous API. For instance, pass a completion block to your getImage
method and call it with in the completion block of the download operation. In this block, do what you need with the image.
这篇关于如何从方法内的块返回变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!