码迷,mamicode.com
首页 > 其他好文 > 详细

NSNotificationCenter需要注意的几个问题

时间:2015-04-11 22:23:58      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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.

来源于:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Notifications/Articles/NotificationCenters.html

 

第一段,简单的来说,它是一个“同步的”消息通知机制. 虽然方法名字是postNotification,但这个玩意并不是异步的,和WIN32 API的PostMessage可是有很大区别哦,只有Observer将消息处理完毕后,消息发送者才会继续执行,所以如果在通知处理的地方要做大量耗时操作的话,很有可能就会带来问题啦。

第二段的意思就是在多线程的应用中,Notification在哪个线程中Post, 就是在那个线程分发,结合第一段,也就在同一个线程中被observer处理。说白了,就是在哪个线程中调用了postNotification或者postNotificationName, observer的回调函数就是在哪个线程中决定,完全取决于发送消息的那个线程, 和注册线程也就是addObserver调用的那个线程无关.

而通常呢,我们会在Observer对象的dealloc方法中去removeObserver, 所以,理论上,如果observer的dealloc和消息发送者的postNotification的方法在不同的线程中调用的话,是有可能会导致Crash的. 

 

NSNotificationCenter需要注意的几个问题

标签:

原文地址:http://www.cnblogs.com/agger0207/p/4418392.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!