NSOperation and SetImage

无人久伴 提交于 2019-12-03 20:27:55

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:

  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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!