Search code examples
iosobjective-cobjective-c-blocksnsoperationnsoperationqueue

NSOperationQueue gets complete notification before completing tasks


I am using NSOperation subclass in my app which will do following 4 tasks in a single operation, i wanted all these 4 tasks to run on background thread so I wrapped up into single NSOperation class, so that I can easily either pause or cancel it

Tasks

  1. long time running calculation
  2. fetching data from core data
  3. Updating to server
  4. Updating coredata

here each has to execute synchronously which means each one is depend on another one except long time running calculation.

Code

// MyOperation.h
@interface MyOperation : NSOperation {
}
@property (nonatomic, getter = isCancelled) BOOL cancelled;
@end

// MyOperation.m
@implementation MyOperation

- (void)cancel
{
   @synchronized (self)
   {
     if (!self.cancelled)
     {
        [self willChangeValueForKey:@"isCancelled"];
        self.cancelled = YES;
        [webServiceOperation cancel]
        [self didChangeValueForKey:@"isCancelled"];
     }
   }
}

- (void)main {
   if ([self isCancelled]) {
    NSLog(@"** operation cancelled **");
    return;
   }    
   @autoreleasepool{
    [self performTasks];
   }
}
- (void)performTasks {

    [self calculate:^{

          if (self.isCancelled)
              return;

          [self fetchDataFromCoredata:^{

                if (self.isCancelled)
                    return;

                //I am using AFNetWorking for updateWebService task so it shall run on separate NSOperation so it would be like nested NSOPeration

                webServiceOperation = [self updateWebService:^{

                                            if (self.isCancelled)
                                            return;

                                            [self updateCoreData:^{

                                                  if (self.isCancelled)
                                                        return;
                                            }];
             }];
        }];


    }];

}
@end

I am assuming that I am not following proper approach because when I tested this code using KVO the NSOperationQueuegets complete notification before it reaches calculate's completion block.

Questions

  1. Is my approach right?
  2. If not, can you some please guide me the right approach?
  3. If it is right approach then why does NSOPerationQueue get complete notification before completion block execution?

Thanks in advance! looking forward your response


Solution

  • Only actually the web call needs to be explicitly asynchronous as your operation will already run on a background thread. So you can simplify the block structure in your code so there isn't so much nesting.

    Then you need to properly construct your operation subclass to handle asynchronous content, as described here.