问题
I'm uisng addObserver:selector:name:object:
in viewDidLoad
.
And I'm using removeObserver:name:object:
in viewWillDisappear:animated:
to remove observer.
What will happen if I failed to remove observer by passing wrong parameter to removeObserver:name:object:
?
(For example, observer isn't removed if I pass wrong notification to parameter name
or wrong object to object
or Observer
)
If the observer still not nil after calling removeObserver:name:object:
, I can find out that removing observer failed because notificationSelector will being called.
But if the observer become nil after calling removeObserver:name:object:
, I can not find out whether removing observer failed or not.
Will observers automatically removed when observer become nil?
Or does notification dispatch table
of NSNotificationCenter
became larger and larger and eventually the app become slow?
EDIT
When I use subclass of UIViewController object for observer, the app doesn't crash after ViewController's dealloc
are called.
But when I use a object of other class, the app crashs after the object's dealloc
are called.
回答1:
Update: From -[NotificationCenter removeObserver:]:
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 this method orremoveObserver:name:object:
before observer or any object specified inaddObserverForName:object:queue:usingBlock:
oraddObserver:selector:name:object:
is deallocated.
Old answer:
Observers are not removed automatically. From the NSNotificationCenter Class Reference:
Important: The notification center does not retain its observers, therefore, you must ensure that you unregister observers (using removeObserver: or removeObserver:name:object:) before they are deallocated. (If you don't, you will generate a runtime error if the center sends a message to a freed object.)
You should therefore call
[[NSNotificationCenter defaultCenter] removeObserver:self];
in your dealloc
method if you are not 100% sure that the observer was not removed previously.
回答2:
You just need to put in the correct Observer for the Observer to be removed. If you pass the wrong parameter to name or object (or nil), the receiver will not use them as criteria for removal.
All Cocoa programs have a default NSNotificationCenter, so once you remove the observers you shouldn't have to worry about the it taking up more memory.
来源:https://stackoverflow.com/questions/11544690/will-observers-automatically-removed-when-observers-become-nil