如何监听发送到iOS NSNotificationCenter的defaultCenter的所有通知?

Ton*_*ony 46 nsnotificationcenter ios

我想收听调度到defaultCenter的所有通知.公共和私人.有谁知道我怎么做到这一点?

Sam*_*Sam 75

使用NSNotificationCenter的addObserverForName:object:queue:usingBlock:OR addObserver:selector:name:object:方法并为名称和对象传递nil.

以下代码应该完成这项工作:

- (void)dumpNotifications {
    NSNotificationCenter *notifyCenter = [NSNotificationCenter defaultCenter];
    [notifyCenter addObserverForName:nil 
                              object:nil 
                               queue:nil 
                          usingBlock:^(NSNotification *notification){
                             // Explore notification
                             NSLog(@"Notification found with:"
                                    "\r\n     name:     %@"
                                    "\r\n     object:   %@"
                                    "\r\n     userInfo: %@", 
                                    [notification name], 
                                    [notification object], 
                                    [notification userInfo]);
                          }];
}
Run Code Online (Sandbox Code Playgroud)

文件

这是关于的文档addObserverForName:object:queue:usingBlock:.特别是,请参阅nameobj参数.

addObserverForName:对象:队列:usingBlock:

向接收方的调度表添加一个条目,其中包含通知队列和要添加到队列的块,以及可选条件:通知名称和发送方.

- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block

参数

名称

要注册观察员的通知的名称; 也就是说,仅使用具有此名称的通知将块添加到操作队列.如果传递nil,则通知中心不会使用通知的名称来决定是否将块添加到操作队列.

OBJ

要将其块添加到操作队列的通知的对象.如果您传递nil,则通知中心不会使用通知的发件人来决定是否将该块添加到操作队列中.

队列

应添加块的操作队列.如果传递nil,则块在发布线程上同步运行.

收到通知时要执行的块.该块由通知中心复制并保存(副本),直到删除观察者注册为止.该块有一个参数:

通知

通知.