如何在if语句中检查NSNotification

时间:2013-03-08 11:46:09

标签: ios objective-c nsnotificationcenter

我正在尝试运行以下代码,除非发送NSNotification。我无法弄清楚如何将NSNotification放在if语句中:

if (!self.subViewControllerProv) {
    self.subViewControllerProv = [[ProvViewController alloc] init];
}


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

回顾一下:如果观察到NSNotification消息,那么allocinit ProvViewController如果没有,那么就不会。{/ p>

2 个答案:

答案 0 :(得分:3)

尝试添加一个实例变量,其中包含通知是否已触发的标志,在-handleNotification:中设置标志,然后检查是否适当。

- (void)handleNotification:(NSNotification*)notification {
    _notificationWasPosted = YES;
}

...

if (!_notificationWasPosted && !self.subViewControllerProv) {
    self.subViewControllerProv = [[ProvViewController alloc] init];
}

答案 1 :(得分:3)

那么做这样的事情呢?

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

然后

-(void) handleNotification {
    //BOOL _hasBeenSent in your interface
    _hasBeenSent = YES;
}

然后在你的代码中

if(_hasBeenSent) {
    NSLog(@"The notification has been sent!");
}