OGeek|极客世界-中国程序员成长平台

标题: ios - 跨多个 Controller 更新对象/模型 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:31
标题: ios - 跨多个 Controller 更新对象/模型

我是 swift 的初学者。所以在我的项目中,我使用了多个对象/模型,我几乎在所有 Controller 中都使用过。我的问题是,当我的对象/模型在任何一个 Controller 中更新时,如何自动更新我的对象/模型(跨所有 Controller )?

执行此操作的正确方法是什么?我该怎么做??



Best Answer-推荐答案


Pass By Value & Pass By Reference的概念。

最适合您的问题的解决方案是使用 Pass By Reference 类型。

如果我们谈论 Swift 编程语言

class 是引用类型,struct 是值类型。

因此,您的模型类应该使用 class 类型构建。

代码示例。

class Dog {
    var breed : String = ""
    var sub_breed = [String]()
    init(_breed:String,_sub_breed:[String]) {
        self.breed = _breed
        self.sub_breed = _sub_breed
    }
}

FirstViewController:

var dogs : [Dog] = [Dog(_breed: “Original”, _sub_breed: [“subBreedType1”, “subBreedType2”])]

SecondViewController: // You are passing reference of dogs to SecondVC

var dogs : [Dog] = []

dogs[0].breed = “Modified”

现在您已经从 SecondViewController 更改了 breed name 的值,如果您返回 FirstViewController 并检查 first element 数组的值将是 “修改”

你可以试试这个想法。

其他解决方案:Model 类Singleton object

谢谢。

关于ios - 跨多个 Controller 更新对象/模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48021248/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4