iOS Adding an Observer


Example

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:

  • NSApplicationDidBecomeActiveNotification
  • NSWindowDidMiniaturizeNotification
  • NSTextViewDidChangeSelectionNotification
  • NSColorPanelColorDidChangeNotification

Swift 2.3

NSNotificationCenter.defaultCenter().addObserver(self, 
                                                 selector: #selector(self.testNotification(_:)), 
                                                 name: "TestNotification", 
                                                 object: nil)

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.