views:

216

answers:

2

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?

+2  A: 

Add an observer to you 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, having it look for the context your registered as your listener. You can make the data you want to retrieve from the NSOperation subclass available via an accessor method/property.

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

Check ou the KVO Programming Guide and the Concurrency Programming Guide for more info.

Also, note that the observer will be received on the same thread as the Operation, so you may need to run code on the main thread if you want to deal with the UI.

Jablair
+2  A: 

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.
Kris Jenkins
will this run on the same thread as the operation too?
Mel
Yes, unless you use performSelectorOnMainThread to specify otherwise.
Brad Larson