Question

- (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?

Was it helpful?

Solution

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;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top