我创建了一个继承自 NSOperation 的 fetchImageOperation 类。它使用 URL 获取图像,然后在完成后触发块。我的问题是,如果我有以下代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Customer *customer = [_customers objectAtIndex:[indexPath row]];
FetchImageOperation *imageOperation = [[FetchImageOperation alloc] initWithURL:[NSURL URLWithString:vegetable.imageURL]];
cell.nameLabel.text = customer.name;
imageOperation.fetchImageOperationCompletionBlock = ^(UIImage *image)
{
[cell.thumbnailImageView setImage:image];
};
[_queue addOperation:imageOperation];
return cell;
}
setImage 方法是默认在主线程(UI Thread)上调用的吗?我可以确认上面的代码有效,它确实设置了 thumbnailaImageView 元素的图像属性。
FetchImageOperation.m 文件:
@implementation FetchImageOperation
-(id) initWithURL:(NSURL *)url
{
self = [super init];
self.url = url;
return self;
}
-(void) main
{
NSData *data = [NSData dataWithContentsOfURL:_url];
UIImage *image = [UIImage imageWithData:data];
if(self.fetchImageOperationCompletionBlock != nil)
{
self.fetchImageOperationCompletionBlock(image);
}
}
@end