复制自
documentation
属于
-[NSNotificationCenter addObserverForName:object:queue:usingBlock:]
:
返回值
作为观察者的不透明物体。
讨论
如果给定的通知触发多个观察者块,则这些块可以彼此同时执行(但在它们的给定队列或当前线程上)。
下面的示例演示如何注册以接收区域设置更改通知。
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
self.localeChangeObserver = [center addObserverForName:NSCurrentLocaleDidChangeNotification object:nil
queue:mainQueue usingBlock:^(NSNotification *note) {
NSLog(@"The user's locale changed to: %@", [[NSLocale currentLocale] localeIdentifier]);
}];
若要注销观察,请将此方法返回的对象传递给removeObserver:。在释放addObserverForName:object:queue:usingBlock:指定的任何对象之前,必须调用removeObserver:或removeObserver:name:object:。
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self.localeChangeObserver];
编辑:
从同一页复制:
另一个常见的模式是通过从观察块中移除观察者来创建一次性通知,如下例所示。
NSNotificationCenter * __weak center = [NSNotificationCenter defaultCenter];
id __block token = [center addObserverForName:@"OneTimeNotification"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSLog(@"Received the notification!");
[center removeObserver:token];
}];