當您發佈通知時,它會導致通知所有註冊觀察員。他們會收到通知,發送消息給他們......由選擇器標識的消息。正如在評論中提到的,您應該而不是使用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];
}
你可能不應該只是記得viewDidLoad中。添加刷新方法,將爲您更新所有視圖。 –
@詹姆斯是正確的,你真的不應該手動調用'viewDidLoad' - 將你想要運行的代碼提取到一個單獨的方法中,並根據需要從'viewDidLoad'中調用它。但什麼不工作?你沒有真正解釋這個問題。 –
對不起,如果我的問題不清楚。在遵循@ Jody的回答後,現在的問題是,當我從我的子視圖發佈通知時,父視圖中的選擇器從不會被調用。你知道這是爲什麼嗎? – user1396737