What type of reference does NSNotificationCenter keep for 'observer's & 'object's?

前端 未结 2 1232
忘了有多久
忘了有多久 2021-02-07 04:16

Can anyone clarify/elucidate the situation with respect to -[NSNotificationCenter addObserver:selector:name:object:]?

  • What types of references are

2条回答
  •  再見小時候
    2021-02-07 04:37

    what types of references are kept by the notification center of the 'observer' and 'object' arguments?

    I believe a weak reference, though that's just from memory (no pun intended).

    what are the best practices for removing observers from the notification center?

    Always remove the registered object from the notification center before they're released. The object's dealloc method is a good place for this if it set up the registration itself, or when you release it if another object is managing the notification subscriptions. Keep this in mind and the above won't matter.

    what are the special concerns for multi-threaded applications, especially WRT the 'object' argument?

    NSNotificationCenter works fine on threads, but if you send a notification from a background thread, the object will receive it on that same thread. Because of this behavior you should use a different approach if you're updating the UI or doing anything else that's not thread safe (or, dispatch the notification from another method on the main thread).

    what are the differences in behavior of this method in GC and non-GC environments?

    I don't remember hearing of anything that you need to worry about, though I haven't used the GC much yet.

    are the any significant differences (from a client perspective) between mobile and desktop environments in this method's behavior?

    Not that I've heard of, no. When you register your object you can choose to register for all notifications or only notifications from a certain object. If you're using notifications heavily the latter may be a little faster, but always test to be sure.

    Also, any pointers to existing articles which cover this would be greatly appreciated. I googled, but was surprised to find little in-depth discussion of these issues (although maybe i didn't use the right magic keywords).

    I think it's more because NSNotificationCenter is pretty easy to use, in general. If you're worried about certain cases, don't be afraid to write a quick test app!

提交回复
热议问题