This is a mirror of official site: http://jasper-net.blogspot.com/

Loading Images Asynchronously on iPhone using NSInvocationOperation

| Monday, May 17, 2010
The iPhone SDK often makes doing things very easy, as long as you know where to look. Loading an Image into an UIImageView is one of these things. The problem I ran into, however, was that loading the image took too much time when performing the operation synchronously. To my surprise it wasn't much harder to load the image on a background thread. This was easily accomplished using NSOperation, specifically the prebuilt subclass NSInvocationOperation.

In a typical situation you might be downloading an image from somewhere on the internet, in this case Flickr. Now this might be a small image, in which case it may not take that long. But that still depends on internet connection, site, and many other factors. So, if you wanted to code it up quick and dirty you might go with something like the following code, which will download the image synchronous and create an image from that data. Finally, it sets the image view's image property to the new image. Downloading the image blocks all user interaction and interface updating, not good for the user's experience.

NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"imageurl.jpg"]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
[imageView setImage:image]; // UIImageView
[image release];
[imageData release];

Read more: Switch on code

Posted via email from jasper22's posterous

0 comments: