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”中,则只需 A 收到通知并不是全部。
感谢您的帮助
i have a class to read barcode, and when i read barcode i post a notification to NSNotificationCenter as below .
-(void)barcodeData:(NSString *)barcode type:(int)type {
barcodeValue = barcode;
[[NSNotificationCenter defaultCenter] postNotificationName:@"BarcodeRead" object:self];
}
then in a few view controller i add observer to get barcode value as like as .
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(BarcodeRead) name:@"BarcodeRead" object:nil];
-(void) BarcodeRead
{
//
}
the question is when a notification is send to notification center, in all of the view which i add observer they get the notification and call the method BarcodeRead, but i want if the application is in view controller "A" just A get the notification and not all of them.
thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常将注册/取消注册代码放入
viewWillAppear
/viewWillDisappear
方法中,以确保通知仅在控制器处于活动状态时显示在控制器中。I usually put the registration/unregistration code into the
viewWillAppear
/viewWillDisappear
methods to ensure the notifications only show up in the controller while it's active.然后,您应该让不应该接收通知的对象在离开屏幕后取消注册为观察者(当然,当它们返回屏幕时重新注册)。
Then you should have the objects that should not receive the notification unregister themselves as observers once they go offscreen (an re-register when they come back onscreen, of course).