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

NSNotificationCenter.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];

PS: It is also worth noting that the number of times an observer has been added has to be exactly the number of times the observer is removed. A rookie mistake is to add the observer in the viewWillAppear: of a UIViewController, but removing the observer in viewDidUnload:, will cause an uneven number of pushes and thus leaking the observer and the notification selector getting called in a superfluous manner.

Feedback about page:

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



Table Of Contents