开发者

Will an NSNotification object retain its "object" and "userInfo" properties and if so, what is the lifespan of those retains?

If I am posting a distributed NSNotification, can I safely release the object passed in as the "object" property? What about this scary mention in the doc that there is "no guarantee" of delivery for distributed notificat开发者_StackOverflow中文版ions?


It won't let me comment on Benedict's answer so let me give you some info from the NSNotification class reference:

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.

In other words, you can register for NSNotifications on any thread, and whatever thread sends the notification will be the thread that the observer responds on. So if you're doing UI stuff, you need to make sure that you perform the selector on the main thread. Otherwise, it doesn't really matter as long as your code is thread-safe.


If you no longer want ownership of object or userInfo then it is safe to release them. If the notification observer want to keep hold of object or userInfo then they should retain them.

Notifications are only delivered to objects that registered for them on the same thread that the notification is being delivered on. There are two ways to avoid confusion:

  1. Only send and register for notifications on the main thread. This doesn't guarantee that things won't got wrong, but it should reduce the possibility of things going wrong. Use the performSelectorOnMainThread: group of methods to do this.

  2. Use Key Value Observing instead of notifications. KVO is not used that much on iOS presumably because iOS doesn't having bindings. KVO are always delivered and are delivered on the thread that the KVO event was raised.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜