NSNotificationCenter有帮助吗?

问题描述:

我有一个课程来阅读条形码,当我阅读条形码时,我会通知NSNotificationCenter如下。NSNotificationCenter有帮助吗?

-(void)barcodeData:(NSString *)barcode type:(int)type { 

    barcodeValue = barcode; 

    [[NSNotificationCenter defaultCenter] postNotificationName:@"BarcodeRead" object:self]; 

} 

然后在几个视图控制器我添加观测得到的条形码值等作为。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(BarcodeRead) name:@"BarcodeRead" object:nil]; 


-(void) BarcodeRead 
{ 
    // 
} 

的问题是何时通知被发送到通知中心,在所有的观点,我补充观察员,他们得到通知并调用该方法BarcodeRead,但我想,如果应用程序是在视图控制器“A “只需要获得通知,而不是全部。

感谢您的帮助

+0

http://*.com/a/2191802/64457 - 为我工作发送一个消息到多个接收器。如果您只想要一个对象获取消息 - 根据您的接收者列表发送不同的消息。例如postNotificationName:@“BarcodeRead_ALL”vs postNotificationName:@“BarcodeRead_TARGET_1”。您可以添加粒度到发布的消息以定位特定的对象 – Paxic

我通常会将注册/注销代码放入viewWillAppear/viewWillDisappear方法中,以确保通知仅在控制器处于活动状态时显示。

那么你应该不应该收到通知注销自己作为观察员,一旦他们去屏幕外(一个重新注册,当他们回来的屏幕,当然)的对象。