0

I am using PageViewController where I may have more than one image as a content. I am getting image as follows from the Service. However, when user clicks to dismiss the viewcontroller while network operation still going on, app crashes.

queue = [[NSOperationQueue alloc] init];
operation = [NSBlockOperation blockOperationWithBlock:^{
            [self addAllImages];
                dispatch_sync(dispatch_get_main_queue(), ^(void) {
                     [self pageViewcontrollerSetup];
            });
        }];
     [queue addOperation:operation];
}

- (void) addAllImages
{
    self.pageImages =[[NSMutableArray alloc] initWithCapacity:self.pageControl.numberOfPages];

    for(id key in [[[pElements objectAtIndex:self.selectedIndexPath.row]objectForKey:@"pdetail"] objectForKey:@"images"]) {
        NSString *productURL = [NSString stringWithFormat:@"%@%@", PRODUCT_URL, [[[[pElements objectAtIndex:self.selectedIndexPath.row]objectForKey:@"pdetail"] objectForKey:@"images"] objectForKey:key]];
        NSData* productData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productURL]];

        if ([UIImage imageWithData:productData]) {
                [self.pageImages addObject:[UIImage imageWithData:productData]];
        }
    }
}

- (void)closeBtnClicked {

    [queue cancelAllOperations];
}

NOTE : I was using GCD (Grand Central Dispatch) for multi-threading, but I came to know that you cannot cancel it, therefore I swicthed to NSOperationQueue

casillas
  • 16,351
  • 19
  • 115
  • 215

1 Answers1

0

Canceling an operation does not magically halt your code dead in its tracks. It is up to your code in the operation to check periodically to see whether the operation has been cancelled, and to bow out if so.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • could you please give me a small example ? I thought `cancelAllOperations` will cancel corresponding thread immediately. if not, then what is the purpose of using `[queue cancelAllOperations];` ? – casillas Mar 29 '17 at 17:16
  • Did you look at the link I posted? It shows you how to check for cancellation within your operation block. – matt Mar 29 '17 at 18:04