简体   繁体   中英

Get the results returned from an NSInvocationOperation

- (void)viewDidLoad
{        
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];        
    NSInvocationOperation *downloadImageOperation = [[NSInvocationOperation alloc] initWithTarget:[ImageDownloader getInstance]
                                                                            selector:@selector(downloadImageSync:)
                                                                              object:@"image url"];
    [operationQueue addOperation:downloadImageOperation];        
    UIImage *imag = [downloadImageOperation result]; // image is always nil here
    imageVIEW.image = imag;
}

Returns the result of the invocation or method. - (id)result Return Value The object returned by the method or an NSValue object containing the return value if it is not an object. If the method or invocation is not finished executing, this method returns nil.

I always get nil for the image. What's wrong with the above code?

Operations on a NSOperationQueue are executed on a separate thread. The operation has not finished executing when you call [downloadImageOperation result] , therefore the result is nil .

You can for example assign the image view at the end of your downloadImageSync: method, but it must be done on the main thread:

dispatch_async(dispatch_get_main_queue(), ^{
    imageVIEW.image = imag;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM