繁体   English   中英

NsoperationQueue取消所有操作在完成操作之前不会被取消

[英]NsoperationQueue Cancel all operations is not cancelled until it finishes the operation

在我看来我有图像视图,图像视图的数据来自Url,图像大约1-3 MB。 如果用户Swipes然后我想加载下一个图像,如果我慢慢滑动,每件事情都可以正常工作但是当我快速滑动时我想取消之前的操作并从新网址开始。

对于Ex。 如果第二和第三张图像的操作位于中间,如果用户滑动4次,我想取消这些并开始下载第4张图像

但是现在在第4张图像的地方我得到第一张第2张图像跟随第3张然后第4张图像出现。

这是我的示例代码

- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)aSwipeGestureRecognizer {


    [BackgroundOperation cancelAllOperations];  // To cancel previous one 


    [self performSelector:@selector(LoadImage) withObject:nil afterDelay:0.1];


}

-(void)LoadImage
{
    BackgroundOperation=[[NSOperationQueue alloc]init];  


    imgvww.image=[UIImage imageNamed:@"loader.png"]; // Place holder    till download finishes 


   [BackgroundOperation addOperationWithBlock:^
     {
         UIImage *img=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[self.ItemDetails objectAtIndex:0] objectForKey:@"ImageUrl"]]]];  // Getting data from URL 

         [[NSOperationQueue mainQueue] addOperationWithBlock:^{


             imgvww.image=img;  //Adding to image view after completion 


         }];

     }];
 }

谢谢。

NSOperationQueue上调用cancelAllOperations只会在每个操作上调用cancel 如果NSOperation没有覆盖cancel那么它永远不会被取消。

一旦启动,就没有取消NSBlockOperation概念。 该块只是执行,就是这样。

如果要指定特殊取消行为(如取消图像下载),则需要子类化NSOperation并覆盖cancel

AFNetworkingSDWebImage有很多这样的例子

要取消图像下载,您需要在NSURLSesionDownloadTask中包含NSOperation ,然后覆盖cancel以在NSURLSesionDownloadTask上调用cancel

取消操作只是将其isCancelled Flag设置为true。

您负责在开始运行之前检查您的操作是否已被取消(或者在运行期间,如果它是长时间运行的操作)。

您可以检查操作块中是否取消了操作,但我建议使用子类,而不是使用块。

取消操作只会将其isCancelled属性更新为YES
要取消操作,您应该执行以下操作:

NSBlockOperation * op = [NSBlockOperation new];
__weak NSBlockOperation * weakOp = op; // Use a weak reference to avoid a retain cycle
[op addExecutionBlock:^{
    // Put this code between whenever you want to allow an operation to cancel
    // For example: Inside a loop, before a large calculation, before saving/updating data or UI, etc.
    if (weakOp.isCancelled) return;

    // Do something..
];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM