我有一个uitableview,它显示每个细胞中的图像,这些图像是在线下载的。
为了进行异步调用,我使用了NSBlockoperation。我更喜欢使用这个,因为我以前用过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个单元格,所以我认为即使我离开视图,它们仍然在队列中。
发布于 2012-09-13 04:08:28
看起来你的代码从来没有超过一个块排队-这是正确的吗?如果不是,则需要向队列发送“取消”,而不是向操作发送。
不管怎样,你的问题很可能是下面这行:
NSData *data = [NSData dataWithContentsOfURL:[newsimages objectAtIndex:indexPath.row]];;该下载正在为您同步完成-因此,如果您在此消息后立即发送“取消”,那么取消将在很长一段时间内看不到。这就是为什么大多数开发人员使用使用异步NSURLConnections的并发NSOperations来进行下载-这样就可以实时获得取消消息。
假设这是ARC,您可以在dealloc中添加日志,以验证操作实际上已完成或已取消,并且已正确释放。注意上面的日志是在返回之后,所以永远不会被调用。你也应该在周围散布更多的isCancelled消息,这样你在被取消后就会尽快停止。
https://stackoverflow.com/questions/12395185
复制相似问题