我有一个 RootVC
,其中包含 MapVC
和 ListVC
的容器 View 。
由于我需要进行 API 调用并在 MapVC
和 ListVC
之间共享结果,因此我创建了一个 RootVCDelegate
。
protocol RootVCDelegate {
func fetch(results: [Object]) -> Void
}
在 prepare(for UIStoryboardSegue:)
中,我分别将 RootVCDelegate
属性设置为 MapVC
或 ListVC
,具体取决于标识符。我知道这行不通,因为委托(delegate)属性只能有一个值。
委托(delegate)模式在这里不起作用,那么如何在这些 View Controller 之间共享异步调用的结果?
最佳答案
您可以将 RootVCDelegate
设为一个委托(delegate)数组,然后当您想要对委托(delegate)执行操作时,执行 delegats.forEach { ..... }
并在分配一个委托(delegate)时执行委托(delegate)只需将委托(delegate)附加到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
}
}
}
这可能就是您所要求的?
关于ios - 在 View Controller 之间共享异步调用的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255593/