Does removeObserver() remove all observers?
Solution 1
Yes, the removeObserver(self)
call will remove all observers that you added using addObserver:selector:name:object:
with an observer of self, regardless of the notification name, object, or selector you specified.
It is a bad idea to use the removeObserver(self)
method anywhere but in your object's deinit method, because some system classes (or subclasses of objects that you define) may have added observers that you don't know about. That method call is a "scorched earth" call the removes ALL observers from the object.
Instead you should call removeObserver:name:object:
and remove only the observers that you added.
Solution 2
Removes all the entries specifying a given observer from the receiver’s dispatch table. https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/index.html#//apple_ref/occ/instm/NSNotificationCenter/removeObserver:
So I guess it'll remove all observers only when all are same as specified by the parameter.
Related videos on Youtube
4thSpace
Updated on September 07, 2020Comments
-
4thSpace almost 4 years
Does the following remove all NSNotificationCenter.defaultCenter there were added by name a view?
NotificationCenter.default.removeObserver(self)
If I have the following in the same view of viewDidLoad(), will they be removed with the single line above?
NotificationCenter.default.addObserver(self, selector: Selector(("method1")), name: UITextField.textDidChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: Selector(("method2")), name: UITextView.textDidChangeNotification, object: nil)
-
4thSpace about 9 yearsI've updated the question. Even though the two observers in the OP have two different method names, the single line of code should remove both right?
-
Duncan C about 9 yearsSee my answer to your question. The answer is yes, but don't use it.
-
4thSpace about 9 yearsIf I remove these by name, which method should I remove them in? I loaded through viewDidLoad(). I don't get any autocomplete for a deinit.
-
4thSpace about 9 yearsYour answer is vague. What "parameter"?
-
Duncan C about 9 yearsSearch for it in the Swift language reference iBook (which is free.) If you add an observer in viewDidLoad (which only gets called once on creation of a view controller) then you need to put the balancing call to removeObserver in a
deinit
method that you add. Yourdeinit
method will be called right before your object gets deallocated. -
4thSpace about 9 yearsI've added a deinit to my UIViewController. How do I test this in the simulator? It doesn't trigger with a home button click or app shutdown.
-
Duncan C almost 9 yearsI didn't say anything about a parameter. My answer has a timestamp of 2:56.