【发布时间】:2012-09-12 19:43:23
【问题描述】:
我有一个 uitableview 显示每个单元格中的图像,这些图像是在线下载的。
为了使这个调用异步,我使用 NSBlock 操作。我更喜欢用这个,因为我以前用过 GCD 但你不能取消 GCD。原因是如果我离开视图,图像会在应用程序的后台下载,当我再次进入前一个视图时,GCD 会让它再次排队,所以最终会有一整堆图像和用户永远不会看到 uitableview。所以这就是我选择 NSBlockoperation 的原因。
但是,我的块并没有被取消。这是我使用的代码(它是 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ):
// Create an operation without any work to do
downloadImageOperation = [NSBlockOperation new];
// Make a weak reference to the operation. This is used to check if the operation
// has been cancelled from within the block
__weak NSBlockOperation* operation = downloadImageOperation;
// Give the operation some work to do
[downloadImageOperation addExecutionBlock: ^() {
// Download the image
NSData *data = [NSData dataWithContentsOfURL:[newsimages objectAtIndex:indexPath.row]];;
UIImage *image = [[UIImage alloc] initWithData:data];
NSLog(@"%@",image);
// Make sure the operation was not cancelled whilst the download was in progress
if (operation.isCancelled) {
return;
NSLog(@"gestopt");
}
if (image != nil) {
NSData* imageData = UIImagePNGRepresentation(image);
[fileManager createFileAtPath:path contents:imageData attributes:nil];
cell.imageView.image = image;
cell.imageView.layer.masksToBounds = YES;
cell.imageView.layer.cornerRadius = 15.0;
}
// Do something with the image
}];
// Schedule the download by adding the download operation to the queue
[queuee addOperation:downloadImageOperation];
我已使用此代码取消:
-(void)viewDidDisappear:(BOOL)animated {
[downloadImageOperation cancel];
}
但是,我的 NSLog 告诉我,即使在我的视图消失后(我在那里放了一个 nslog),仍然有块。
2012-09-12 21:32:31.869 App[1631:1a07] <UIImage: 0x3965b0>
2012-09-12 21:32:32.508 App[1631:1907] <UIImage: 0x180d40>
2012-09-12 21:32:32.620 App[1631:707] view dissappear!
2012-09-12 21:32:33.089 App[1631:3a03] <UIImage: 0x3a4380>
2012-09-12 21:32:33.329 App[1631:5a03] <UIImage: 0x198720>
注意:视图中每次显示 4 个单元格,所以我认为即使我离开视图,它们仍在队列中..
【问题讨论】:
标签: objective-c ios asynchronous uitableview nsblockoperation