omniscian
omniscian

Reputation: 55

NSOperation and SetImage

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

Answers (4)

Mark Johnson
Mark Johnson

Reputation: 1115

Try using HJCache, its made for this kind of thing: http://www.markj.net/hjcache-iphone-image-cache/

Upvotes: 0

Matthias Bauch
Matthias Bauch

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

kevboh
kevboh

Reputation: 5245

You have a few options here:

  1. You could hand a reference to your imageview to the GetImage operation, and assign to imageview.image when the operation gets the image.
  2. 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.
  3. 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.

Upvotes: 0

Icky
Icky

Reputation: 1055

The ImageView has an image property, try accessing this.

Upvotes: -2

Related Questions