gpt4 book ai didi

objective-c - NSBlock操作没有被取消

转载 作者:行者123 更新时间:2023-11-29 04:25:27 25 4
gpt4 key购买 nike

我有一个 uitableview,它显示每个单元格中的图像,这些图像是在线下载的。

为了使此调用异步,我使用 NSBlockoperation。我更喜欢用这个,因为我以前用过GCD,但你不能取消GCD。原因是,如果我离开 View ,图像会在应用程序的后台下载,当我再次进入前一个 View 时,GCD 会让它再次排队,所以最终会出现一整堆图像和用户永远不会看到 uitableview。这就是我选择 NSBlockoperation 的原因。

但是,我的区 block 不会被取消。这是我使用的代码(它是 - (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 告诉我,即使我的 View 消失(我在那里放了一个 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>

注意: View 中每次显示 4 个单元格,因此我认为即使我离开 View ,它们仍然在队列中。

最佳答案

看来您的代码从来没有超过一个排队的 block - 这是正确的吗?如果没有,那么您需要将“取消”发送到队列而不是操作。

无论如何,您的问题很可能是这一行:

NSData *data = [NSData dataWithContentsOfURL:[newsimages objectAtIndex:indexPath.row]];;

该下载正在为您同步完成 - 因此,如果您在此消息之后发送“取消”,则很长一段时间内都不会看到取消。这就是为什么大多数开发人员使用异步 NSURLConnections 来使用并发 NSOperations 来进行下载 - 以便实时获取取消消息。

假设这是 ARC,您可以在 dealloc 中添加日志来验证操作实际上已完成或已取消,并已正确释放。 [请注意,上面的日志是在返回之后的,因此永远不会被调用。您还应该散布更多 isCancelled 消息,以便在取消后尽快停止。]

关于objective-c - NSBlock操作没有被取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12395185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com