Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSOperation and NSOperationQueue callback

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

Now my NSOperation is finished. I just want to know that it is finished in my class and to have the operation pass data to that class. How is this typically done?

like image 814
Mel Avatar asked Dec 30 '09 05:12

Mel


2 Answers

I use the delegate pattern - that was the approach recommended to me by the guys at an Apple Developer Conference.

The scaffolding:

  1. Set up a protocol MyOperationDelegate with a setResult:(MyResultObject *) result method.
  2. Have whoever needs the result implement that protocol.
  3. Add @property id<MyOperationDelegate> delegate; to the NSOperation subclass you've created.

The work:

  1. When you create your operation, but before you queue it, tell it who should receive the result. Often, this is the object that creates the operation: [myOperation setDelegate: self];
  2. At the end of your operation's main function, call [delegate setResult: myResultObject]; to pass the result on.
like image 119
Kris Jenkins Avatar answered Oct 13 '22 10:10

Kris Jenkins


Another alternative... if your need to do some work when the operation is complete, you could wrap that work up in a block and use a dependancy. This 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");
}];
like image 28
Robert Avatar answered Oct 13 '22 10:10

Robert