NSNotificationCenter and safe multithreading

后端 未结 2 576
青春惊慌失措
青春惊慌失措 2020-12-31 18:08

Given that objects may be deallocated even while a method invocation is in progress (link)*, is it safe for an object to register for and receive notificati

2条回答
  •  灰色年华
    2020-12-31 18:58

    NSNotificationCenter does not take a strong reference to the object, so the observer must be removed before deallocation. When ARC is enabled, if handleNotification is being called, the observer will not be deallocated since calling handleNotification will increase its retain count. If observer is deallocated before the notification is posted, NSNotificationCenter will remove it from the observers as you write in dealloc method so that handleNotification will not be called. NSNotificationCenter calls notification handlers synchronously while notification is posted.

提交回复
热议问题