Search code examples
iosobjective-cnsoperationqueue

Convert GCD to NSOperationqueue


The task can be cancelled if while using NSOperation whereas if I use GCD, then once I assign the task to queue then we are not able to cancel it, therefore I wonder how could I convert my following implementation in GCD to NSOperation

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
     [self addAllImages];
      dispatch_sync(dispatch_get_main_queue(), ^(void) {
             [self pageControlSetUp];
             self.fullScreenImageView.hidden = YES;
       });
 })

Solution

  • NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
      [self addAllImages];
      dispatch_sync(dispatch_get_main_queue(), ^(void) {
        [self pageControlSetUp];
        self.fullScreenImageView.hidden = YES;
      });
    }];
    
    
    [queue addOperation:operation];
    
    
    //cancel operation
    [operation cancel];
    
    //or to cancell all operations
    [queue cancelAllOperations];