objective-c - 使用委托(delegate)通过多个 View Controller 传回数据

标签 objective-c ios delegation

在 IOS 中,我非常喜欢在 View 之间传递数据,这些 View 直接在使用prepareforsegue 向前传递数据和委托(delegate)将数据传递回来之间进行分隔。

我遇到的问题是,我正在构建一个通过 4 个 View 进行排序的应用程序,然后当用户在第四个 View 上按 Enter 键时,我会弹出其余 View 以返回到第一个 View Controller ,这是 View ,但我不知道如何将数据委托(delegate)回第一个 View 。

我认为问题在于在第一个 View Controller 中设置委托(delegate)。我无法像通常使用 segue.destinationviewcontroller 那样设置它,因为该 View Controller 尚不存在。我应该把它设置在其他地方吗?执行此操作的正确方法是什么?

最佳答案

不要使用委托(delegate)来传递数据,请考虑使用 NSNotificationCenter在这种情况下,您的 View Controller 之间进行通信。

在您的第一个 View Controller 中,您将注册以监听通知:

- (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

}

在您的第一个 View Controller 的 dealloc 方法中,请务必取消注册为观察者(以避免潜在的崩溃):

-(void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

然后在第四个 View Controller 中,按下 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];

关于objective-c - 使用委托(delegate)通过多个 View Controller 传回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12545167/

上一篇:iOS6 方向

下一篇:iphone - 下拉列表实现

相关文章:

objective-c - addTarget :action:forControlEvents - UISwitch in TableView - sender ok, 事件始终为 0x0

iphone - 如何正确管理我的应用程序网址?

ios - 为什么带有 subview Controller 的 UIViewController 有时会返回children[0].isEmpty = true?

iphone - 类别授权

jquery - 悬停事件会冒泡吗?

ios - UIStackView 中的第一个基线和最后一个基线属性

objective-c - 从char*数组到二维数组再返回算法出错

ios - iOS中UICollectionView如何流畅播放多个视频?

ios - MKCircle 平滑调整大小

ios - cellforRowAtIndexPath 效率如何?