2013-03-08 101 views
2

我试图运行以下代码,除非发送NSNotification。我无法弄清楚如何把NSNotification if语句:如何在if语句中检查NSNotification

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


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

来回顾一下:如果遵守了NSNotification消息,那么allocinitProvViewController如果不是的话就不要。

回答

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

尝试添加一个持有标志的实例变量,以确定通知是否已触发,将标志设置为-handleNotification:,然后检查是否适当。

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

... 

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