问题
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