Reputation: 2002
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
Upvotes: 1
Views: 295
Reputation: 2515
If you want to use NSOperation just follow "Wain's" answer you need process task sequentially.
You can still go with your nested block structure using GCD and avoiding use NSOperation.
NSOperation vs Grand Central Dispatch
Upvotes: 0
Reputation: 52538
The performTasks method doesn't actually perform any tasks. It dispatches tasks to queues or calls methods that dispatch tasks to queues. When the dispatching is done, performTasks is finished and your NSOperationQueue will treat it as finished, even though the task is still executing.
I don't think there's much reason to use NSOperation here. Just use GCD.
Upvotes: 0
Reputation: 119031
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.
Upvotes: 1