简体   繁体   English

如何在if语句中检查NSNotification

[英]How to check for an NSNotification in an if statement

I'm trying to run the following code, unless a NSNotification is sent. 我正在尝试运行以下代码,除非发送了NSNotification I can't figure out how to put the NSNotification in the if statement: 我不知道如何将NSNotification放在if语句中:

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


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

to recap: if the NSNotification message is observed then alloc and init the ProvViewController if not then don't. 到概括:如果NSNotification观察消息。然后allocinitProvViewController如果不是那么没有。

Try adding an instance variable holding a flag for whether the notification has fired or not, set the flag in -handleNotification:, and then check for if when appropriate. 尝试添加一个带有标志的实例变量,该标志用于通知是否已触发,在-handleNotification:中设置该标志,然后检查是否合适。

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

...

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

Well what about doing something like this: 那么做这样的事情呢:

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

and then 接着

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

And then in your code 然后在你的代码中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM