听 NSNotifications 的正确方法
Proper way to listen to NSNotifications
如果我在视图控制器上有 2 个通知有 2 个观察者,这样是否合适:
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:@"note1" object:nil];
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:@"note2" object:nil];
或者我只是通过将 nil 传递给名称然后检查 handleNotification 函数中发送的通知来找出哪个通知是 运行:
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:nil object:nil];
谢谢。
实际上,如果您将 nil
作为名称传递,您将收到所有通知,无论其名称如何(不仅仅是您想要的两个)。最好分别订阅每一个,给它们命名。
Apple 文档摘录:
If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.
(这一点,起初我不清楚,我误读了它,以为你不会收到任何通知)。
您可以对两者使用相同的 callback/listener,并根据收到的通知决定要做什么。
您可以在 NSNotificationCenter
上创建一个类别来处理多个名称的注册,这就是类别的用途!
如果我在视图控制器上有 2 个通知有 2 个观察者,这样是否合适:
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:@"note1" object:nil];
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:@"note2" object:nil];
或者我只是通过将 nil 传递给名称然后检查 handleNotification 函数中发送的通知来找出哪个通知是 运行:
[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotifications:) name:nil object:nil];
谢谢。
实际上,如果您将 nil
作为名称传递,您将收到所有通知,无论其名称如何(不仅仅是您想要的两个)。最好分别订阅每一个,给它们命名。
Apple 文档摘录:
If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.
(这一点,起初我不清楚,我误读了它,以为你不会收到任何通知)。
您可以对两者使用相同的 callback/listener,并根据收到的通知决定要做什么。
您可以在 NSNotificationCenter
上创建一个类别来处理多个名称的注册,这就是类别的用途!