2013-06-27 26 views
2

我正在开发具有与外部附件通信的应用程序。该应用程序有几个请求发送到外部附件。通知中心 - Obervers不能正常工作

我的问题:

我使用观察者在不同的地方(类),我添加了以下观察员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]; 

首届观察员的作品非常好,但我与其他两个人有问题。直到第一个使用完毕,他们才会回应。我需要添加其他东西吗?

的流程如下:

  1. 发送到EXT-ACC的要求和消防标志知道哪些观察者将返回的数据

  2. EXT-ACC与数据

  3. 响应
  4. 接收方法将通知推送到通知中心。

  5. 在1旗帜将采取数据的观察员(在这一点上,我需要删除的通知,因为没有人会需要它吗?)。

+1

你想达到什么目的?如果你为相同的通知注册3个观察者,那么每个事件都将被调用(按顺序)。 –

+0

对不起,好像观察者不醒目的通知,但observer1开头 –

+0

如果我需要移动“的addObserver”到viewWillAppear中 –

回答

2

看起来你对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 { 
     // ???? 
    } 
} 
+0

好吧,我不知道,因此另外一个问题就是,我需要做的事情像进入观察者后“删除”通知?或者它由应用程序自动处理? –

+0

您必须在dealloc中调用removeObserver,因为您要在viewDidLoad中添加观察者。如果您将添加观察者代码移至其中一个viewXAppear方法,则应该在其中一个viewXDisappear方法中取消订阅。 – Lance

+0

感谢您的帮助XJones :) –