Search code examples
iphoneobjective-ccocoa-touchobserver-patternnsnotifications

NSNotificationCenter: How long does it take to perform an operation


I want to know how long does it take from posting a notification to getting the notification.

The reason is that I want to find out if the observer pattern is suitable for me. I don't want that another view controller can change the value before the notification has been sent and processed. I'm afraid that another process (thread?) is faster and the value will be overwritten when it shouldn't.


Solution

  • A notification center delivers messages synchronously, which means that the postNotification: method does not return until all objects registered to receive the notification have processed the notification. In other words, you can think of it as taking no time between posting a notification and receiving the notification.

    There are a few extra things you'll need to be aware of:

    Notifications are received on the same thread in which they are posted. If you move a notification over to the main thread using performSelectorOnMainThread:withObject:waitUntilDone:, you can break the synchronous behavior if waitUntilDone is set to NO. If waitUntilDone is set to YES, the thread passing the notification will block until the main thread has finished performing the specified action.

    There is no guarantee of the order in which a notification will be received by its observers. If a single notification has multiple observers, don't rely on those observers receiving the notification in any particular order.

    Given the above, and knowing which thread is posting notifications in your application and which thread needs to process them, you should be able to figure out whether the observer pattern will work for you.