Significant lag when loading an image using UIImage from a URL asynchronously

I am trying to write an iPad application that downloads an image from a url. I use the following image upload code:

    url = [NSURL URLWithString:theURLString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    img = [[UIImage alloc] initWithData:data];
    [imageView setImage:img];
    [img release];
    NSLog(@"Image reloaded");

All this code is added to NSOperationQueue as an operation, so it will load asynchronously and will not cause my application to block if the image web server is slow. I added the NSLog line so that I could see it on the console when this code completed execution.

I constantly noticed that the image is updated in my application after about 5 seconds. AFTER code completion. However, if I use this code myself without putting it in an NSOperationQUeue, it seems to update the image almost immediately.

The delay is not completely caused by the slow web server ... I can load the image URL in Safari and it takes less than a second to load, or I can load it with the same code without NSOperationQueue, and it loads much faster.

Is there a way to reduce the lag before displaying my image, but keep using NSOperationQueue?

+5
source share
2 answers

According to the documentation, the code you wrote is invalid. UIKit objects cannot be called anywhere other than the main thread. I bet that what you do works in most cases, but does not change the display, while the screen is updated by coincidence for some other reason.

Apple , URL-, . NSURLConnection runloop . , NSData, , , , , ,

url = [NSURL URLWithString:theURLString];
NSData *data = [NSData dataWithContentsOfURL:url];
[self performSelectorOnMainThread:@selector(setImageViewImage:) withObject:data waitUntilDone:YES];

...

- (void)setImageViewImage:(NSData *)data
{
    img = [[UIImage alloc] initWithData:data];
    [imageView setImage:img];
    [img release];
    NSLog(@"Image reloaded");
}

performSelectorOnMainThread , - , , , . "" - , NSOperation. , , , waitUntilDone:YES. -, , .

, (, JPEG PNG), . , UIImage, , , C CoreGraphics. , .

+6

UIKit . , , NSURLConnection. , , .

, [imgView setImage: img] :

[imageView performSelectorOnMainThread:@selector(setImage:)
                          withObject:img
                       waitUntilDone:NO];
+1

All Articles