2012-09-07 51 views
0


上週我問了這個問題:Refresh the entire iOS app @Jim建議我使用通知中心。我無法弄清楚如何使用通知,我被告知要問另外一個問題,我試了整整一週的時間來自己解決問題,所以這裏就是這樣。NSnotification center not working iOS

我有多個子視圖的視圖。其中一個子視圖是一個搜索欄(不是桌面視圖,只是一個自定義文本框),用戶可以在這裏搜索一個新用戶,整個應用程序將逐個屏幕更新。

當用戶點擊搜索子視圖中的GO按鈕時,我會調用服務器來獲取所有數據。這之後,我張貼此通知:

[self makeServerCalls]; 

[[NSNotificationCenter defaultCenter] postNotificationName:@"New data" object:Nil]; 

現在在我的父視圖控制器的初始化我有一個聽衆

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidLoad) name:@"New data" object:nil]; 

我知道這很可能是錯誤的,所以任何人都可以給我如何解釋在我的情況下正確使用通知?或者如果有更好的方式做我想做的事情。

感謝您給我的任何幫助。

+0

你可能不應該只是記得viewDidLoad中。添加刷新方法,將爲您更新所有視圖。 –

+0

@詹姆斯是正確的,你真的不應該手動調用'viewDidLoad' - 將你想要運行的代碼提取到一個單獨的方法中,並根據需要從'viewDidLoad'中調用它。但什麼不工作?你沒有真正解釋這個問題。 –

+0

對不起,如果我的問題不清楚。在遵循@ Jody的回答後,現在的問題是,當我從我的子視圖發佈通知時,父視圖中的選擇器從不會被調用。你知道這是爲什麼嗎? – user1396737

回答

3

當您發佈通知時,它會導致通知所有註冊觀察員。他們會收到通知,發送消息給他們......由選擇器標識的消息。正如在評論中提到的,您應該而不是使用viewDidLoad。考慮這個...

- (void)newDataNotification:(NSNotification *notification) { 
    // Do whatever you want to do when new data has arrived. 
} 

在一些早期的代碼(viewDidLoad中是一個很好的候選人):

[[NSNotificationCenter defaultCenter] 
    addObserver:self 
     selector:@selector(newDataNotification:) 
      name:@"New data" 
     object:nil]; 

這是一個可怕的名字,順便說一句。好吧。此註冊表示,只要通知以任何對象的名稱"New data"發佈,您的self對象就會發送消息newDataNotification:NSNotification對象。如果要限制要從中接收消息的對象,請提供非零值。

現在,當你發送通知,你可以這樣做簡單,就像你在你的代碼所做的:

[[NSNotificationCenter defaultCenter] postNotificationName:@"New data" object:nil]; 

,這將確保(實際目的)[self newDataNotification:notification]被調用。現在,您可以隨通知一起發送數據。所以,假設新數據由newDataObject表示。既然你從任何對象接受通知,您可以:

[[NSNotificationCenter defaultCenter] 
    postNotificationName:@"New data" 
        object:newDataObject]; 

,然後在你的處理器:

- (void)newDataNotification:(NSNotification *notification) { 
    // Do whatever you want to do when new data has arrived. 
    // The new data is stored in the notification object 
    NewData *newDataObject = notification.object; 
} 

或者,你可以在用戶信息字典傳遞數據。

[[NSNotificationCenter defaultCenter] 
    postNotificationName:@"New data" 
        object:nil 
       userInfo:@{ 
          someKey : someData, 
         anotherKey : moreData, 
          }]; 

然後,你的處理程序看起來像這樣...

- (void)newDataNotification:(NSNotification *notification) { 
    // Do whatever you want to do when new data has arrived. 
    // The new data is stored in the notification user info 
    NSDictionary *newData = notification.userInfo; 
} 

當然,你可以做同樣的事情與塊API,這是我比較喜歡。

無論如何,請注意,您必須移除您的觀察者。如果你有一個viewDidUnload你應該把它放在那裏。此外,要確保它會在dealloc還有:

- (void)dealloc { 
    // This will remove this object from all notifications 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 
+0

謝謝你的迴應。但它仍然不適合我。父視圖如何知道通知已發佈?這是自動的嗎?我相信我的通知選擇器永遠不會被調用。 – user1396737

+0

是的,它是「自動的」。確保你使用了正確的選擇器。 'foo'與'foo:'不同。此外,您可以設置斷點並跟蹤進度。如果您仍然遇到問題,則需要發佈無法使用的代碼。 –