繁体   English   中英

使用委托将数据通过多个视图控制器传回

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM