Search code examples
iosobjective-cnsoperationnsoperationqueue

NSOperationQueue cancelAllOperations not work when viewWillDisappear


My code:

NSOperationQueue *queue;

-(void)viewDidLoad
{
    queue = [NSOperationQueue new];
    NSOperation* loadImgOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(refresh) object:nil];
    [queue addOperation:loadImgOp];

}

-(void)refresh
{
   [self operationFirst];         
   [self operationSecond];
   ... 
   [self operationFive];
   dispatch_async(dispatch_get_main_queue(), ^{
      [self.tableView reloadData];
   });

}

- (void)viewWillDisappear:(BOOL)animated {
   [super viewWillDisappear:animated];
   [queue cancelAllOperations];     
}

When I call new ViewController, then -(void)refresh continues work. cancelAllOperations not working.


Solution

  • You can't in your current configuration. You should add a cancelled property and check it throughout the method.

    Calling cancel on the queue marks the operations as cancelled and prevents new operations from running, but it doesn't terminate running operations. It's up to each operation to manage its cancellation. In then are of an invocation it can't do anything as it has already called the target method.