Adding an Observer
suggest changeNaming 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 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents