2011-01-30 50 views
2

我需要使用一个线程才能从Web中检索图像并将其分配到图像视图中。NSOperation和SetImage

我有子类的NSOperation,并从我的视图控制器喜欢把它称为:

NSOperation *operation = [[[GetImage alloc] init] autorelease]; 

[queue addOperation:operation]; 

我得到图像细腻,但我怎么去分配是形象,是在我的NSOperation类?我有存储在一个UIImage称为RetrievedImage图像:

NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]]; 

retrievedImage = [[UIImage alloc] initWithData:imageData]; 

[imageData release]; 

我现在该如何获取到我的ViewController的ImageView的?

谢谢

回答

4

您使用委托。

你的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; 
} 

的重要组成部分,是你检查,如果你是在主线程上运行的一部分。
您无法从另一个线程访问界面元素。所以,如果你是不是在主线程,你开始在主线程同样的方法

-2

ImageView有一个图像属性,请尝试访问它。

+0

我试图设置的ImageView setImage两个NSOperation类和ViewController类中,都没有工作。他们不会崩溃,只是没有任何反应。 – omniscian 2011-01-30 20:12:15

+0

在将imageview添加到视图之前,您是否设置了此项?这应该是工作.... – Icky 2011-01-30 20:16:52

0

你这里有几个选项:

  1. 你可以交给你的ImageView到的getImage操作的参考,并指定当操作获取图像imageview.image。
  2. 您可以继承UIImageView并让它听取通知,例如GetImageFinishedNotification - 操作在完成时附加图像并发布此通知,并且imageview接收它并显示图像。
  3. 您可以设置具有UIImage属性的模型对象。您的视图控制器保留在此对象上,并在其图像属性上设置Key-Value观察值。该操作也保留在其上并在获取图像时设置图像属性。 ViewController会收到更改提示并设置正确的图像视图。

我个人更喜欢NSNotification这种东西 - 它实际上非常类似于foursquare的fully-loaded项目。