我想在可与Codable一起使用的Objective-C和Swift混合应用程序中使用Realm,并且Realm Object可以导出到Objective-C;
class Person2 : RLMObject,Decodable {
@objc dynamic var name = ""
convenience init(_ name:String) {
self.init()
self.name = name
}
}
class RepairShop2 : RLMObject,Decodable {
@objc dynamic var name = ""
@objc dynamic var contact:Person2?
@objc dynamic var persons = RLMArray<Person2>(objectClassName: Person2.className())
private enum RepairShop2CodingKeys: String, CodingKey {
case name
case contact
case persons
}
convenience init(name: String, contact: Person2, persons: RLMArray<Person2>) {
self.init()
self.name = name
self.contact = contact
self.persons = persons
}
convenience required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: RepairShop2CodingKeys.self)
let name = try container.decode(String.self, forKey: .name)
let contact = try container.decode(Person2.self, forKey: .contact)
let personArray = try container.decode(RLMArray<AnyObject>, forKey: .persons)
// this line error: Ambiguous reference to member 'decode(_:forKey:)'**
let persons = RLMArray<Person2>(objectClassName: Person2.className())
persons.addObjects(personArray)
self.init(name: name, contact: contact, persons: persons)
}
}
let personArray = try container.decode(RLMArray<AnyObject>, forKey: .persons)
// this line error: Ambiguous reference to member 'decode(_:forKey:)'**
RLMArray.self我也尝试过,失败
如何编写RLMArray的解码类型?
答案 0 :(得分:0)
RLMRealm
不符合Decodable
,因此您将无法立即将其解析为RLMRealm
。而是尝试类似的东西:
let persons = RLMArray<Person2>(objectClassName: Person2.className())
persons.addObjects(try container.decode([Person2].self, forKey: .persons) as NSFastEnumeration)
作为旁注。将不同的域混合到一个模型中不是一个好主意,它可能会在以后出现。