通知由名称由以下方式组成的全局NSString对象标识:
Name of associated class+ Did | Will+ UniquePartOfName+Notification
例如:
NSApplicationDidBecomeActiveNotification
NSWindowDidMiniaturizeNotification
NSTextViewDidChangeSelectionNotification
NSColorPanelColorDidChangeNotification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.testNotification(_:)), name: "TestNotification", object: nil)
NSNotificationCenter.default.addObserver(self, selector: #selector(self.testNotification(_:)), name: NSNotification.Name(rawValue: "TestNotification"), object: nil)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testNotification:) name:@"TestNotification" object:nil];
PS:还值得注意的是,添加观察者的次数必须与移除观察者的次数完全相同。一个菜鸟的错误是在viewWillAppear:UIViewController的中添加观察者,但是在中删除观察者viewDidUnload:将导致推送次数不均,从而泄漏观察者和通知选择器,从而不必要地被调用。