Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does removeObserver() remove all observers?

Tags:

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) 
like image 819
4thSpace Avatar asked Apr 21 '15 02:04

4thSpace


People also ask

Do I need to remove observers Swift?

As of iOS 9 (and OS X 10.11), you don't need to remove observers yourself, if you're not using block based observers though. The system will do it for you, since it uses zeroing-weak references for observers, where it can.

How do you delete observers in Swift?

Removing registered observer For Selector approach, use NotificationCenter. default. removeObserver(self, name: notificationName , object: nil) , to remove the observer. For Block based approach, save the token you obtained by registering for notification in a property.

How do I delete an observer in Objective C?

When removing an observer, remove it with the most specific detail possible. For example, if you used a name and object to register the observer, use removeObserver:name:object: with the name and object.


1 Answers

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.

like image 141
Duncan C Avatar answered Sep 18 '22 14:09

Duncan C