Ios NSNotificationCenter帮助?
我有一个阅读条形码的类,当我阅读条形码时,我会向NSNotificationCenter发布通知,如下所示Ios NSNotificationCenter帮助?,ios,nsnotificationcenter,Ios,Nsnotificationcenter,我有一个阅读条形码的类,当我阅读条形码时,我会向NSNotificationCenter发布通知,如下所示 -(void)barcodeData:(NSString *)barcode type:(int)type { barcodeValue = barcode; [[NSNotificationCenter defaultCenter] postNotificationName:@"BarcodeRead" object:self]; } 然后在一些视图控制器中,我添
-(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”中,我希望只收到通知,而不是所有通知
感谢您的帮助那么您应该让那些不应该收到通知的对象在离开屏幕后将自己注销为观察者(当然,当它们回到屏幕上时会重新注册).我通常将注册/注销代码放入
视图将出现
/视图将消失
方法中,以确保在控制器处于活动状态时,通知仅显示在控制器中。-对我来说很有效,可以向多个接收者发送一条消息。如果您只希望一个对象获取消息,请根据接收者列表发送不同的消息。例如postNotificationName:@“BarcodeRead_ALL”与postNotificationName:@“BarcodeRead_TARGET_1”。您可以将粒度添加到已发布消息中,以针对特定对象