NSOperation and NSOperationQueue callback

I have a class. Inside this class, I pass NSOperation to an NSOperationQueue that lives in my global variables.

Now my NSOperation is complete. I just want to know that it is completed in my class and that the operation data is passed to this class. How is this usually done?

+8
objective-c iphone cocoa-touch cocoa
source share
3 answers

I use the delegate template - this was the approach recommended by the guys at the Apple Developer Conference.

Forests:

  • Configure the MyOperationDelegate protocol using the setResult:(MyResultObject *) result method.
  • For those who need a result, this protocol is implemented.
  • Add @property id<MyOperationDelegate> delegate; to the subclass of NSOperation that you created.

Job:

  • When you create your operation, but before its turn, tell her who should get the result. Often this is the object that creates the operation: [myOperation setDelegate: self];
  • At the end of your main operation function, call [delegate setResult: myResultObject]; to pass the result.
+23
source share

Another alternative ... if you need to do any work after the operation is completed, you can wrap it in a block and use the dependency. It is very simple, especially with NSBlockOperation.

 NSOperationQueue* myQueue = [[NSOperationQueue alloc] init]; NSBlockOperation* myOp = [NSBlockOperation blockOperationWithBlock:^{ // Do work }]; NSBlockOperation* myOp2 = [NSBlockOperation blockOperationWithBlock:^{ // Do work }]; // My Op2 will only start when myOp is complete [myOp2 addDependency:myOp]; [myQueue addOperation:myOp]; [myQueue addOperation:myOp2]; 

Also you can use setCompletionBlock

 [myOp setCompletionBlock:^{ NSLog(@"MyOp completed"); }]; 
+16
source share

Add an observer to your class that listens for changes to the isFinished value of the NSOperation subclass

 [operation addObserver:self forKeyPath:@"isFinished" options:NSKeyValueObservingOptionNew context:SOME_CONTEXT]; 

Then implement the following method, looking for the context registered as a listener. You can make the data that you want to retrieve from a subclass of NSOperation accessible through the method / property of the access method.

 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 

Check out KVO Programming and Parallel Programming.

Also note that the observer will be received in the same thread as the operation, so you may need to run the code in the main thread if you want to work with the user interface.

+15
source share

All Articles