添加观察者

命名惯例

通知由全局 NSString 对象标识,其名称以这种方式组成:

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

例如:

  • 则 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:值得注意的是,添加观察者的次数必须与观察者被移除的次数完全相同。新手错误是在 UIViewController 的 viewWillAppear:中添加观察者,但是删除 viewDidUnload:中的观察者将导致推送次数不均匀,从而泄漏观察者并且通知选择器以多余的方式被调用。