簡體   English   中英

如何在if語句中檢查NSNotification

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

我正在嘗試運行以下代碼,除非發送了NSNotification 我不知道如何將NSNotification放在if語句中:

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


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

到概括:如果NSNotification觀察消息。然后allocinitProvViewController如果不是那么沒有。

嘗試添加一個帶有標志的實例變量,該標志用於通知是否已觸發,在-handleNotification:中設置該標志,然后檢查是否合適。

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

...

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

那么做這樣的事情呢:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM