NSOperation和SetImage [英] NSOperation and SetImage
问题描述
我需要使用一个线程才能从Web检索图像并将其分配到图像视图中.
I need to use a thread in order to retrieve an image from the web and assign it into an image view.
我将NSOperation子类化,并从我的视图控制器中调用它,例如:
I have subclassed NSOperation and called it from my view controller like:
NSOperation *operation = [[[GetImage alloc] init] autorelease];
[queue addOperation:operation];
我可以很好地处理图像,但是如何分配NSOperation类中的图像呢?我将图像存储在名为RetrievedImage的UIImage中:
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];
现在如何将其放入ViewController的ImageView中?
How do I now get that into the ImageView of my ViewController?
谢谢
推荐答案
您使用委派.
您的NSO操作:
- (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;
}
重要的部分是检查是否在主线程上运行的部分.
您不能从另一个线程访问接口元素.因此,如果您不在主线程上,则可以在主线程上启动相同的方法
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
这篇关于NSOperation和SetImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!