Search code examples
cocoamultithreadingnsnotificationsnstask

NSNotification and Multithreading


I'm trying to get the notification NSTaskDidTerminateNotification in my multithreaded app but I can't get it working. It does seem to work when I tested it on a single threaded app. In init I have [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(taskDidEnd:) name: NSTaskDidTerminateNotification object: myTask]; and I'm quite sure that it gets called because other objects (like myTask) are being initiated there. And the taskDidEnd: method is defined as

- (void)taskDidEnd: (NSNotification *)aNotification
{
     NSLog(@"Task succeeded.");
}

And in dealloc the observer gets removed.

This all happens in an object which is initiated inside a separate thread and I would like to receive that notification inside the same object.


Solution

  • Did you run the run loop on that thread? If not, NSTask won't notice that the task ended (or the task won't have ended yet) and won't post the notification.