iOS 添加观察者

示例

命名约定

通知由名称由以下方式组成的全局NSString对象标识:

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

例如:

  • NSApplicationDidBecomeActiveNotification

  • NSWindowDidMiniaturizeNotification

  • NSTextViewDidChangeSelectionNotification

  • NSColorPanelColorDidChangeNotification

迅捷2.3

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

迅捷3

NSNotificationCenter.default.addObserver(self, 
                                         selector: #selector(self.testNotification(_:)), 
                                         name: NSNotification.Name(rawValue: "TestNotification"), 
                                         object: nil)

目标C

[[NSNotificationCenter defaultCenter] addObserver:self 
                                      selector:@selector(testNotification:) 
                                      name:@"TestNotification" 
                                      object:nil];

PS:还值得注意的是,添加观察者的次数必须与移除观察者的次数完全相同。一个菜鸟的错误是在viewWillAppear:UIViewController的中添加观察者,但是在中删除观察者viewDidUnload:将导致推送次数不均,从而泄漏观察者和通知选择器,从而不必要地被调用。