Search code examples
iosnsnotification

Which is better, dispatching NSNotification on the main thread or handing the notification on the main thread


I understand that there may not be a right answer, but I was very curious to find out what people think about this issue or if there are pros and cons for the following approaches. First example dispatches the notification on the main thread and second example handles notification in the main thread. If you were to choose one of the two approaches, which one and why?

dispatch_async(dispatch_get_main_queue(), ^{
   [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName"
                                                       object:nil];
}); 


- (void)handleNotification:(NSNotification *)notification {
   dispatch_async(dispatch_get_main_queue(), ^{
       [self updateUI];
   });
}

It makes sense to dispatch the notification on the main thread if you know that some of the handlers need to deal with UI elements. However, if there are multiple notification post sites, then this becomes a potential bug prone thing. I would rather want to dispatch to the main thread in the notification handler, so that each handler has a complete control over this.

I appreciate any feedback you have.


Solution

  • I would prefer the second approach, where the sender is also using the current execution context. This is more efficient. Dispatching unnecessarily on the main thread should be avoided. It should be clearly documented, though.

    The receiver, on the other hand, is the only instance knowing if there are any constraints for its code regarding the execution context. That is, if there is none, it can just use the current execution context. Otherwise, it should dispatch to whatever thread/queue which is required for the code.

    So, we certainly agree ;)