Adding an Observer

suggest change

Naming Convention

Notifications are identified by global NSString objects whose names are composed in this way:

Name of associated class + Did | Will + UniquePartOfName + Notification

For example:

Swift 3

NotificationCenter.default.addObserver(self, 
                                         selector: #selector(self.testNotification(_:)), 
                                         name: NSNotification.Name(rawValue: "TestNotification"), 
                                         object: nil)

Objective-C

[[NSNotificationCenter defaultCenter] addObserver:self 
                                      selector:@selector(testNotification:) 
                                      name:@"TestNotification" 
                                      object:nil];

The number of times an observer is added must match the number of times it is removed. A common mistake is to add the observer in viewWillAppear: but remove it in viewDidUnload:. viewDidUnload is not called on iOS 6 or later, so the remove never runs, the observer leaks, and the selector can be called extra times. Remove it in deinit or in the method paired with where you added it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents