Realm 中的动态属性

Dynamic properties in Realm

我开始在 iOS 8 或更高版本上使用 Realm 并查看 Realm 中的文档。我注意到所有属性前面都有 dynamic 关键字。这在 Realm 中是必需的吗?我已阅读有关关键字的 Apple 文档,可在此处找到。 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html

是的,对于正常的 var 属性是强制性的。来自 realm docs.

Realm model properties need the dynamic var attribute in order for these properties to become accessors for the underlying database data.

There are two exceptions to this: List and RealmOptional properties cannot be declared as dynamic because generic properties cannot be represented in the Objective-C runtime, which is used for dynamic dispatch of dynamic properties, and should always be declared with let.

dynamic 关键字允许 Realm 收到模型变量更改的通知,然后将它们反映到数据库中。

在 Swift 3 中,我们这样声明我们的 属性

dynamic var Name : String = ""

在 Swift 4 中,我们这样声明我们的 属性

@objc dynamic var Name : String = ""