NSNotification and NSThread
-
08-03-2021 - |
Question
I create an object on a seperate thread using NSThread.
NSThread* myThread = [[[NSThread alloc] initWithTarget:self selector:@selector(createNewObject:) object:elements] autorelease];
[myThread start]; // Actually start the thread
That Object waits for an event. When that event occurs a notification is posted on the default notification center.
My AppController observes that notification and runs a selector.
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(myMethod:) name:MyNotification object:nil];
Question: Does the method (myMethod:) from the selector run on the main thread or on the thread from above (myThread) ?
Solution
Same thread in which you post the notification.
In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself. (Source)
Footnote: Objects can't wait for events. Objects just exist. Methods can wait for events.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow