代码之家  ›  专栏  ›  技术社区  ›  user6354073

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

  •  0
  • user6354073  · 技术社区  · 7 年前

    我有一个 RootVC 具有的容器视图 MapVC ListVC . 因为我需要进行API调用,并在两者之间共享结果 MapVC公司 列表VC ,我创建了 RootVCDelegate .

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

    在里面 prepare(for UIStoryboardSegue:) I分别设置 根VCDelegate 属性到 MapVC公司 列表VC 取决于标识符。我知道这行不通,因为委托属性只能有一个值。

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   mmr118    7 年前

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

    这可能就是你想要的?