Will observers automatically removed when observers become nil?
ios, iphone, objective-c, observer-pattern
Solution
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 or `removeObserver:name:object:` before observer or any object specified in `addObserverForName:object:queue:usingBlock:` or `addObserver: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.
Problem
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.