[英]How to pass data back from multiple view controllers to root view controller using delegate? Ios 7
[英]Use A delegate to pass data back through multiple view controllers
在IOS中,我非常樂於在使用prepareforsegue向前傳遞數據和委托將數據傳遞回之間直接隔離的視圖之間傳遞數據。
我遇到的問題是,我正在構建一個可以通過4個視圖進行篩選的應用程序,然后當用戶在第四個視圖上按回車鍵時,我彈出其余視圖以返回到第一個視圖控制器及其視圖。我不知道如何將數據委托回到第一個。
我相信問題在於在第一個視圖控制器中設置委托。 我無法像通常使用segue.destinationviewcontroller那樣設置它,因為該視圖控制器尚不存在。 我應該把它放在其他地方嗎? 正確的方法是什么?
在這種情況下,可以考慮使用NSNotificationCenter在視圖控制器之間進行通信,而不是使用委派來傳遞數據。
在第一個視圖控制器中,您將注冊以收聽通知:
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleFourthViewSubmit:)
name:@"fourthViewSubmit"
object:nil];
}
並創建發送通知時要運行的方法:
- (void)handleFourthViewSubmit:(NSNotification *)notification {
NSDictionary *theData = [notification userInfo]; // theData is the data from your fourth view controller
// pop views and process theData
}
在第一個視圖控制器的dealloc方法中,請確保取消注冊為觀察者(以避免潛在的崩潰):
-(void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
然后在您的第四個視圖控制器中,在按下Enter鍵時廣播通知:
// note: dataDict should be an NSDictionary containing the data you want to send back to your first view controller
[[NSNotificationCenter defaultCenter] postNotificationName:@"fourthViewSubmit"
object:self
userInfo:dataDict];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.