我想在混合的Objective-C和Swift应用程序中使用Realm,并且可以将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)


作为旁注。将不同的域混合到一个模型中不是一个好主意,它可能会在以后被使用。

关于swift - 带有解码器的RLMArray快速:对成员错误的含糊引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51633392/

10-12 05:32