NSNotificationCenter是iOS中常用的消息通知機制,不過在使用過程中有幾點需要注意的問題.
直接貼Apple 的官方文檔吧:
A notification center delivers notifications to observers synchronously. In other words, when posting a notification, control does not return to the poster until all observers have received and processed the notification. To send notifications asynchronously use a notification queue, which is described in Notification Queues.
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.
來源於:
第一段,簡單的來說,它是一個“同步的”消息通知機制. 雖然方法名字是postNotification,但這個玩意並不是異步的,和WIN32 API的PostMessage可是有很大區別哦,只有Observer將消息處理完畢后,消息發送者才會繼續執行,所以如果在通知處理的地方要做大量耗時操作的話,很有可能就會帶來問題啦。
第二段的意思就是在多線程的應用中,Notification在哪個線程中Post, 就是在那個線程分發,結合第一段,也就在同一個線程中被observer處理。說白了,就是在哪個線程中調用了postNotification或者postNotificationName, observer的回調函數就是在哪個線程中決定,完全取決於發送消息的那個線程, 和注冊線程也就是addObserver調用的那個線程無關.
而通常呢,我們會在Observer對象的dealloc方法中去removeObserver, 所以,理論上,如果observer的dealloc和消息發送者的postNotification的方法在不同的線程中調用的話,是有可能會導致Crash的.