在视图控制器之间共享异步调用的结果

时间:2018-01-15 00:32:52

标签: ios swift asynchronous uiviewcontroller

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

protocol RootVCDelegate {
    func fetch(results: [Object]) -> Void
}
prepare(for UIStoryboardSegue:)中的

我根据标识符分别将RootVCDelegate属性设置为MapVCListVC。我知道这不起作用,因为委托属性只能有一个值。

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

1 个答案:

答案 0 :(得分:0)

你可以让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
        }
    }
}

这可能是你要求的?