问题描述
使用Swift 4和Realm 3.0.1,我想将Realm对象的列表存储在父Realm的属性中目的.我遇到了以下问题:
Using Swift 4 and Realm 3.0.1, I'd like to store a list of Realm objects in a property of a parent Realmobject. I ran into the following problem:
在Swift 4中,应保留在Realm中的属性必须为@objc dynamic
,例如@objc dynamic var id: String = ""
.但是,无法以这种方式存储Realm的Array替换类型List
:@objc dynamic var children: List<Child>? = nil
导致此编译器错误:
In Swift 4, properties that should be persisted into Realm have to be @objc dynamic
, e.g. @objc dynamic var id: String = ""
. However, Realm's Array replacement type, List
, can not be stored that way: @objc dynamic var children: List<Child>? = nil
causes this compiler error:
有关更多背景信息,请参见以下完整示例:
For more context, here's a full example:
final class Child: Object {
@objc dynamic var name: String = ""
}
final class Parent: Object {
// this fails to compile
@objc dynamic var children1: List<Child>?
// this compiles but the children will not be persisted
var children2: List<Child>?
}
那么还有另一种在Realm和Swift 4中存储对象列表的方法吗?
So is there another way to store object lists in Realm and Swift 4?
推荐答案
领域List
永远不能是nil
,并且它们不需要@objc dynamic
.它们只能是let
,尽管我在文档中找不到特别注明的内容,但是有一个评论来自特定领域的贡献者
Realm List
s can never be nil
, and they don’t need the @objc dynamic
. They should only be let
, although I can't find that specifically called out in the documentation, there is a comment from a realm contributor that calls it out specifically
对于文档.
let dogs = List<Dog>()
这篇关于如何在Swift 4中保留Realm List属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!