gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:37:50 30 4
gpt4 key购买 nike

我想收听发送到 defaultCenter 的所有通知。公共(public)和私有(private)。有谁知道我该怎么做?

最佳答案

使用 NSNotificationCenter 的 addObserverForName:object:queue:usingBlock:或者 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]);
}];
}

文档

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

addObserverForName:object:queue:usingBlock:

Adds an entry to the receiver’s dispatch table with a notification queue and a block to add to the queue, and optional criteria: notification name and sender.

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

Parameters

name

The name of the notification for which to register the observer; that is, only notifications with this name are used to add the block to the operation queue. If you pass nil, the notification center doesn’t use a notification’s name to decide whether to add the block to the operation queue.

obj

The object whose notifications you want to add the block to the operation queue. If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to add the block to the operation queue.

queue

The operation queue to which block should be added. If you pass nil, the block is run synchronously on the posting thread.

block

The block to be executed when the notification is received. The block is copied by the notification center and (the copy) held until the observer registration is removed. The block takes one argument:

notification

The notification.

关于ios - 我如何监听发送到 iOS NSNotificationCenter 的 defaultCenter 的所有通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7954905/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com