Ios 通知中心-OBerver工作不正常

Ios 通知中心-OBerver工作不正常,ios,objective-c,push-notification,nsnotificationcenter,Ios,Objective C,Push Notification,Nsnotificationcenter,我正在开发一个应用程序,它必须与外部附件进行通信。应用程序有多个请求要发送到外部附件 我的问题是: 我在不同的地方(类)使用观察者,我在viewDidLoad中添加以下观察者: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observer1:) name:EADSessionDataReceivedNotification object:nil]; [[NSNotif

我正在开发一个应用程序,它必须与外部附件进行通信。应用程序有多个请求要发送到外部附件

我的问题是:

我在不同的地方(类)使用观察者,我在
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的观察者将获取数据(此时我是否需要删除通知,因为没有其他人需要它?)


  • 看来您对通知中心的工作方式有误解。您正在注册对象(
    self
    )以观察通知
    EADSessionDataReceivedNotification
    三次,每次都使用自己的选择器(
    observer 1
    observer 2
    observer 3

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

    你想达到什么目标?如果您为同一通知注册了3个观察者,那么每个事件都会(按顺序)调用这三个观察者。抱歉,看起来观察者没有捕捉到通知,但一开始是observer1。我不知道是否需要将“addobserver”移动到viewWillAppearOk,所以另一个问题是,我是否需要执行“删除”之类的操作进入观察者后的通知?或者它是由应用程序自动处理的?您必须在Dealoc中调用removeObserver,因为您要在viewDidLoad中添加观察员。如果将“添加观察者”代码移动到其中一个viewXAppear方法,则应取消订阅其中一个viewXDisappear方法。