2013-03-08 100 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]; 
}