我正在开发一个必须与外部附件通信的应用程序。该应用程序有多个请求发送到外部附件。
我的问题:
我在不同位置(类)使用观察器,在viewDidLoad
中添加了以下观察器:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(observer1:)
name:EADSessionDataReceivedNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(observer2:)
name:EADSessionDataReceivedNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(observer3:)
name:EADSessionDataReceivedNotification object:nil];
第一个观察员工作得很好,但其他两个却遇到了问题。在使用第一个之前,他们不会响应。我是否需要添加其他内容?
流程如下:
最佳答案
您似乎对NSNotificationCenter
的工作方式有误解。您正在注册对象(self
)以观察通知EADSessionDataReceivedNotification
三次,每次都有其自己的选择器(observer1
,observer2
,observer3
)。
因此,发生的事情对于您编写的代码是正确的。发布EADSessionDataReceivedNotification
后,NSNotificationCenter
将指定的选择器发送给每个观察者。没有取消通知的条件逻辑或方法。
根据您的描述,听起来您应该只观察一次通知并检查您的标志以确定如何处理。就像是:
// observe notificaton
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataReceived:) object:nil];
// notification handler
- (void)dataReceived:(NSNotification *)notification {
if (someCondition) {
[self handleDataCondition1];
}
else if (aSecondCondition) {
[self handleDataCondition2];
}
else if (aThirdCondition) {
[self handleDataCondition3];
}
else {
// ????
}
}