iOS NSNotificationCenter Adding an Observer

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any iOS Question?