Yuriy Fedchenko
Yuriy Fedchenko

Reputation: 33

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?

Upvotes: 0

Views: 255

Answers (1)

mag_zbc
mag_zbc

Reputation: 6992

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.

Upvotes: 1

Related Questions