我正在开发一个必须与外部附件通信的应用程序。该应用程序有多个请求发送到外部附件。

我的问题:

我在不同位置(类)使用观察器,在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];

第一个观察员工作得很好,但其他两个却遇到了问题。在使用第一个之前,他们不会响应。我是否需要添加其他内容?

流程如下:
  • 发送请求到ext-acc并触发一个标志,以了解哪个观察者将获取返回的数据
  • ext-acc响应数据
  • 接收器方法将通知推送到通知中心。
  • 标志为1的观察者将获取数据(在这一点上,我需要删除通知,因为没有其他人需要它吗?)。
  • 最佳答案

    您似乎对NSNotificationCenter的工作方式有误解。您正在注册对象(self)以观察通知EADSessionDataReceivedNotification三次,每次都有其自己的选择器(observer1observer2observer3)。

    因此,发生的事情对于您编写的代码是正确的。发布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 {
            // ????
        }
    }
    

    10-07 19:28
    查看更多