is it ok to use of a notification to communication back to the main thread of an IOS app? (cf performSelectorOnMainThread)

2 Solutions Collect From Internet About “is it ok to use of a notification to communication back to the main thread of an IOS app? (cf performSelectorOnMainThread)”

Actually there is a gottcha; you’ll crash randomly! That has been my experience. This has to do with the fact that the object receiving the notification does so on the same thread as the notification’s sender.

From the Apple iOS Documentation on Notification Centers:

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.

This will inevitably cause you headaches.

If the notification is being received by something on the main thread, I’ve found that popping into the main thread from the background thread to issue a notification is the safest way to go about this. It is quite simple to do:

//Call this to post a notification and are on a background thread      
- (void) postmyNotification{
  [self performSelectorOnMainThread:@selector(helperMethod:) withObject:Nil waitUntilDone:NO];

//Do not call this directly if you are running on a background thread.
- (void) helperMethod{
  [[NSNotificationCenter defaultCenter] postNotificationName:@"SOMENAME" object:self];

Unfortunately this introduces a subtle coupling between the sender and receiver in that you are modifying the sender to accommodate the receiver.

An even better solution, as XJones points out, is to have the sender send out the notification on whatever thread it decides to, and then to make the listener responsible for using the proper thread to perform whatever action it needs to.

Hope that was helpful.

Yep, notifications can be used for this purpose. you can use any method you like (protocols, notifications, direct messaging) to communicate between objects across threads. Which one you choose depends on what you feel is most appropriate. Notifications are great when the object posting the notification doesn’t know anything about the objects observing the notification. If you send a message (e.g. performSelectorOnMainThread) then the object sending the message does need to know about the object it is sending the message to (typically through a protocol).