2012-10-23 34 views
0

我試圖在我的Storyboard中使用NSNotification。在故事板中使用NSNotification

當我不使用故事板時,此代碼有效。

這是ViewController1:

- (IBAction) buttonClickedListener2:(id)sender { 
    [[NSNotificationCenter defaultCenter] 
    postNotificationName:@"TestNotification" 
    object:self]; 
} 

這是ViewController2:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
     [[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(receiveTestNotification:) 
                name:@"TestNotification" 
                object:nil]; 

     NSLog(@"initWithNib"); 
    } 
    return self; 
} 

- (void) receiveTestNotification:(NSNotification *) notification 
{ 
    // [notification name] should always be @"TestNotification" 
    // unless you use this method for observation of other notifications 
    // as well. 

    if ([[notification name] isEqualToString:@"TestNotification"]) 
     NSLog (@"Successfully received the test notification!"); 
} 

它是什麼毛病碼?正如我所說我想讓它在Storyboard中運行。

我很感謝你給我一些關於如何在STORYBOARD中使用NSNotification的toturials。

回答

2

故事板不使用initWithNibName,因此您添加觀察者的代碼部分無法運行。你應該能夠通過設置一個斷點來看到它。修復程序將與

- (id)initWithCoder:(NSCoder *)aDecoder 
{ 
    self = [super initWithCoder:aDecoder]; 
    if (self){ 
     //statements 
    } 
    return self; 
} 
+0

是的,你對initWithNibName完全正確。但是當我使用'initWithCoder'時,它會顯示一個警告:'控制到達非空函數結束。它不起作用。即使我無法使用Push導航到第二個viewController。 – Ali

+0

@Ali可能是你錯過了initWithCoder方法的返回值寫爲' - (id)initWithCoder:(NSCoder *)aDecoder' – Kamarshad

+0

是的,但沒有奏效。當我們導航到第二個ViewController時調用'initWithCoder'。 – Ali

0

代碼看起來不錯。

這裏的問題可能是,您發佈NotificationViewController1並將Notification添加到ViewController2

檢查發佈前是否已正確添加Notification,有可能在您嘗試發佈notification時未添加notification

還有一件事就是正確調試檢查是否調用initWithNibName。 我認爲故事板不使用initWithNibName因此您應該使用initWithCoder:(NSCoder *)aDecoder而不是initWithNibName。

+0

是的,你是對的。你有沒有任何例子可以告訴我如何在故事板中以正確的方式使用NSNotification? – Ali

+0

@Ali一件事只是正確調試檢查是否initWithNibName調用或不。 – Kamarshad

3

那麼請不要在initWithNibNameawakeFromNib被添加觀察者更換

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self){ 
     //statements 
    } 
    return self; 
} 

initWithNibName不被稱爲故事板。

例如:

- (void)awakeFromNib { 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(receiveTestNotification:) 
               name:@"TestNotification" 
               object:nil]; 
} 
+0

當我導航到第二個視圖,然後再次導航到第一個:它的工作。但不是一開始。因爲'initWithCoder'或'awakeFromNib'在我導航之前不會被調用。有什麼想法嗎? – Ali

+0

如果'viewController'對象不存在,則不應該收到通知。如果你有這樣的通知執行一些動作,然後在'applicationDidFinishLaunchingWithOptions'中註冊它,並指向一些數據模型方法,這樣它將準備一些數據,以便稍後可以在'viewController'中使用它,例如'viewWillAppear'中的重新加載一些表格。 –

+0

感謝您的幫助。 +1點。 – Ali