我想在混合Objective-C&Swift应用程序与Codable和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的解码类型?
RLMRealm
不符合Decodable
,因此您无法立即将其解析为RLMRealm
。相反,可以尝试以下方法:
let persons = RLMArray<Person2>(objectClassName: Person2.className())
persons.addObjects(try container.decode([Person2].self, forKey: .persons) as NSFastEnumeration)
作为旁注。将不同的领域混合到一个模型中是个坏主意,以后可能会有影响。