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

siva krishna picture siva krishna · Aug 29, 2015 · Viewed 12.6k times · Source

In my view i have image view, the data for image view comes form Url, the images are around 1-3 MB . If the user Swipes then i want to load the next image, Every thing works fine if swiped slowly, But when i swiped Fastly I want to Cancel the previous operation and start with new url.

For Ex. if user swipes 4 times if the operations for 2nd and 3rd images is in the middle, i want to cancel those and start downloading 4 th image

But now In the place of 4th image I’m getting first 2nd image follows 3rd and then 4 th image appears.

Here is my sample code

- (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 


         }];

     }];
 }

Thank you.

Answer

DBoyer picture DBoyer · Aug 29, 2015

Calling cancelAllOperations on an NSOperationQueue will simply call cancel on each of its operations. If the NSOperation does not override cancel then its never going to get cancelled.

There is no concept of cancelling an NSBlockOperation once it has started. The block simply executes and thats that.

If you want to specify special cancel behaviour (like cancelling your image download) you need to subclass NSOperation and override cancel.

There are many examples of this in AFNetworking or SDWebImage

To cancel an image download you need to wrap up an NSURLSesionDownloadTask in an NSOperation and then override cancel to call cancel on the NSURLSesionDownloadTask