【问题标题】:NSNotificationCenter help?NSNotificationCenter 帮助?
【发布时间】:2011-11-06 22:04:16
【问题描述】:

我有一个类来读取条形码,当我读取条形码时,我会向 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 获取通知,而不是全部。

感谢您的帮助

【问题讨论】:

  • stackoverflow.com/a/2191802/64457 - 帮助我将一条消息发送给多个接收者。如果您只希望一个对象获取消息 - 根据您的接收者列表发送不同的消息。例如 postNotificationName:@"BarcodeRead_ALL" 与 postNotificationName:@"BarcodeRead_TARGET_1"。您可以为发布的消息添加粒度以针对特定对象

标签: ios nsnotificationcenter


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    那么你应该让那些不应该收到通知的对象在它们离开屏幕后取消注册为观察者(当然,当它们回到屏幕上时重新注册)。

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 2011-06-20
      • 2011-07-28
      • 2011-10-04
      • 2011-08-03
      • 2011-11-27
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      相关资源
      最近更新 更多