如果我在视图控制器上有两个通知有两个观察者是合适的吗?
[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文档:
如果传递nil,通知中心不会使用通知的名称来决定是否将其传递给观察者。
(这一点,起初,我不清楚,我误解了,以为你不会收到任何通知)。
您可以为两者使用相同的回调/侦听器,并根据收到的通知决定要做什么。
你可以在NSNotificationCenter
上创建一个类别来处理多个名称的注册,这就是类别的作用!