I need to use a thread in order to retrieve an image from the web and assign it into an image view.
I have subclassed NSOperation and called it from my view controller like:
NSOperation *operation = [[[GetImage alloc] init] autorelease];
[queue addOperation:operation];
I get the image fine but how do I go about assigning that image that is in my NSOperation class? I have the image stored in a UIImage called RetrievedImage:
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
retrievedImage = [[UIImage alloc] initWithData:imageData];
[imageData release];
How do I now get that into the ImageView of my ViewController?
Thanks
you use delegation.
Your NSOperation:
- (void)main {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://sstatic.net/stackoverflow/img/apple-touch-icon.png"]];
UIImage *image = [UIImage imageWithData:data];
[delegate fetchedImage:image];
[pool drain];
}
your delegate:
- (void)fetchedImage:(UIImage *)image {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:_cmd withObject:image waitUntilDone:NO];
return;
}
self.imageView.image = image;
}
the important part is the part where you check if you are running on the main thread.
You can't access interface elements from another thread. So if you aren't on main thread, you start the same method on the main thread
You have a few options here:
- You could hand a reference to your imageview to the GetImage operation, and assign to imageview.image when the operation gets the image.
- You could subclass UIImageView and have it listen to a notification, say GetImageFinishedNotification- the operation posts this notification with the image attached when it finishes, and the imageview receives it and displays the image.
- You could set up a model object that has a UIImage property. Your viewcontroller retains on this object and sets up Key-Value observing on its image property. The operation also retains on it and sets the image property when it gets the image. The viewcontroller is alerted to the change and sets the right imageview.
I personally prefer NSNotification for this sort of thing- it's actually pretty similar to foursquare's fully-loaded project.
Try using HJCache, its made for this kind of thing: http://www.markj.net/hjcache-iphone-image-cache/
The ImageView has an image property, try accessing this.
来源:https://stackoverflow.com/questions/4845088/nsoperation-and-setimage