【问题标题】:Share results of asynchronous call between view controllers在视图控制器之间共享异步调用的结果
【发布时间】:2018-01-15 00:32:52
【问题描述】:

我有一个RootVC,其中包含MapVCListVC 的容器视图。 由于我需要进行 API 调用并在MapVCListVC 之间共享结果,因此我创建了一个RootVCDelegate

protocol RootVCDelegate {
    func fetch(results: [Object]) -> Void
}

prepare(for UIStoryboardSegue:)中,我根据标识符分别将RootVCDelegate属性设置为MapVCListVC。我知道这行不通,因为委托属性只能有一个值。

委托模式在这里不起作用,那么如何在这些视图控制器之间共享异步调用的结果?

【问题讨论】:

    标签: ios swift asynchronous uiviewcontroller


    【解决方案1】:

    您可以将RootVCDelegate 设置为一个代表数组,然后当您想要对代表执行时执行delegats.forEach { ..... } 并且在分配代表时只需将代表附加到delegates

    例子:

    // Delegate Protocol
    protocol RootVCDelegate {
        fetch(results: [Objects]) //returning Void does nothing so no need to write it
    }
    
    // RootVC
    class RootVC {
        delegates: [RootVCDelegate]
    
        prepare(for segue: UIStoryboardSegue) {
            let destination = (segue.destination as? UINavigationController).rootViewController ?? segue.destination  // how I like to handle things if there's a possibility of a UINavigationController housing my UIViewController
            switch destination {
            case _ as MapVC: delegates.append(destination)
            case _ as ListVC: delegates.append(destination)
            default: return
            }
        }
    }
    

    这可能是你想要的?

    【讨论】:

    • 谢谢,这看起来可以解决问题。但是,我最终使用了 NotificationCenter。
    • 很好,这将是我的下一个建议,但不知道你对它有多熟悉。想给你知道的东西! NotificationCenter 是一个很好的解决方案 :)
    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 2013-06-19
    • 2016-02-04
    相关资源
    最近更新 更多