views:

849

answers:

2

I have an NSOperation. When it is finished I fire a NSNotificationCenter to let the program know that the NSoperation is finished and to update the gui.

To my understanding listeners to the NSNotification will not run on the main thread because the NSOperation is not on the main thread.

How can I make it so that the listeners run on the main thread when I fire my event?

[[NSNotificationCenter defaultCenter] postNotificationName:@"myEventName" object:self]; 
+4  A: 

You can use performSelectorOnMainThread:withObject:waitUntilDone: with using a helper method, in a similar fashion to the following example.

.....
[self performSelectorOnMainThread:@selector(fireNotification) withObject:nil waitUntilDone:YES];
...

- (void)fireNotification {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"myEventName" object:self]; 
}

If you don't wait until being done, you will need to consider the cases where other threads may refer to the object which could be already cleaned up before the main thread gets invoked.

notnoop
+1  A: 

If you're on 10.6, you can also use setCompletionBlock:. It's used like this:

NSOperation*op= .... ;
[op setCompletionBlock:^{
    dispatch_async(dispatch_get_main_queue(),^{
        code to be run on the main thread after the operation is finished.
    });
}];

For general introduction on blocks and GCD, this article was extremely helpful. I found GCD & setCompletionBlock easier to read than NSNotification. One caveat is, well, it only runs on 10.6!

Yuji
If the "iPhone" tag is used, the asker is probably not on 10.6.
Alex Reynolds
You're right, Alex. Stupid me.
Yuji