简体   繁体   中英

How NSNotification center manage it observe objects?

In old apple guid said: "For example, when you register an object with a notification center, the notification center stores a weak reference to the object and sends messages to it when the appropriate notifications are posted. When the object is deallocated, you need to unregister it with the notification center to prevent the notification center from sending any further messages to the object, which no longer exists" In swift 4 we have 2 methods to observe: 1) NotificationCenter.default.addObserver(object, selector: 2) NotificationCenter.default.addObserver(forName: ... (with block)) In the second case Notification center capture block and retain everything in it, so you should be careful with using self in it

Im try to find information about how in 1 case the observer object is managed by the notificaton center, is it still get weak reference for it or it was change to strong and probably can make memory leak, if you will not unregister in time?

According to documentation of addObserver(_:selector:name:object:) :

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method. Otherwise, you should call removeObserver(_:name:object:) before observer or any object passed to this method is deallocated.

And since observer's dealloc is called, there's no memory leak here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM