我需要使用线程,以便从web检索图像,并将其分配到图像视图中。
我继承了NSOperation的子类,并在视图控制器中调用它,如下所示:
NSOperation *operation = [[[GetImage alloc] init] autorelease];
[queue addOperation:operation];我得到的图像很好,但是如何分配NSOperation类中的图像呢?我将图像存储在一个名为RetrievedImage的UIImage中:
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
retrievedImage = [[UIImage alloc] initWithData:imageData];
[imageData release];我现在如何将其放入我的ViewController的ImageView中?
谢谢
发布于 2011-01-31 04:19:57
您可以使用委派。
您的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];
}您的代表:
- (void)fetchedImage:(UIImage *)image {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:_cmd withObject:image waitUntilDone:NO];
return;
}
self.imageView.image = image;
}重要的部分是检查您是否在主线程上运行的部分。
您不能从另一个线程访问接口元素。因此,如果你不在主线程上,你可以在主线程上启动相同的方法
发布于 2011-01-31 04:11:52
这里有几个选项:
我个人更喜欢在这类事情上使用NSNotification --它实际上非常类似于foursquare的fully-loaded项目。
发布于 2011-01-31 10:23:58
尝试使用HJCache,它是为这种事情而生的:http://www.markj.net/hjcache-iphone-image-cache/
https://stackoverflow.com/questions/4845088
复制相似问题