How to persist a Realm List property in Swift 4?

邮差的信 提交于 2020-01-14 10:27:32

问题


Using Swift 4 and Realm 3.0.1, I'd like to store a list of Realm objects in a property of a parent Realm object. I ran into the following problem:

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:

Property cannot be marked @objc because its type cannot be represented in Objective-C

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>?
}

So is there another way to store object lists in Realm and Swift 4?


回答1:


Realm Lists 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

There is a cheat sheet for properties in the documentation.

let dogs = List<Dog>()


来源:https://stackoverflow.com/questions/47180007/how-to-persist-a-realm-list-property-in-swift-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!