gpt4 book ai didi

ios - 写入后删除类上的可选属性

转载 作者:行者123 更新时间:2023-11-30 12:43:24 24 4
gpt4 key购买 nike

我正在开发一个应用程序,使用 Swift 3.0.2 和 Realm 2.4.2 编写,面向 iOS 10.0。

我有这个数据模型:

class User: Object {

var company: Company? = Company()
dynamic var password = ""
dynamic var email = ""

func persist() {
let realm = try! Realm()
try! realm.write {
realm.add(self)
}
print(company)
}
}

class Company: Object {
dynamic var id = ""
dynamic var name = ""
}

为了保存用户的数据,我使用以下代码:

let user = User()
user.email = "john@apple.com"
user.password = "hey"

user.company?.name = "apple"
user.company?.id = "12"

// here, if I check with debugger, all variable are properly filled
user.persist()

// here : company is = nil
// it is nil at the 'print(company)
// it is not nil before

有人能解释一下为什么这样做吗?

最佳答案

您的 company 属性必须使用 dynamic 修饰符声明,以便 Realm Swift 能够提供从底层 Realm 文件中检索值的 getter。如果没有 dynamic 修饰符,Swift 编译器会生成对底层实例变量的访问,该变量不包含从 Realm 文件加载的对象的任何数据。

关于ios - 写入后删除类上的可选属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41969605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com