简体   繁体   中英

How to check for an NSNotification in an if statement

I'm trying to run the following code, unless a NSNotification is sent. I can't figure out how to put the NSNotification in the if statement:

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.

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.

- (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!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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