新增觀察者

命名慣例

通知由全域性 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:中的觀察者將導致推送次數不均勻,從而洩漏觀察者並且通知選擇器以多餘的方式被呼叫。