Reputation: 55
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
Upvotes: 2
Views: 640
Reputation: 1115
Try using HJCache, its made for this kind of thing: http://www.markj.net/hjcache-iphone-image-cache/
Upvotes: 0
Reputation: 90117
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
Upvotes: 4
Reputation: 5245
You have a few options here:
I personally prefer NSNotification for this sort of thing- it's actually pretty similar to foursquare's fully-loaded project.
Upvotes: 0