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
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 NSOperationQueue
gets complete notification before it reaches calculate's completion block.
Questions
NSOPerationQueue
get complete notification before completion block execution?Thanks in advance! looking forward your response
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.