قالب وردپرس درنا توس
Home / IOS Development / IOS – How to implement Codable while using Realm

IOS – How to implement Codable while using Realm



When you have List in the Realm model, you must implement Codable (Encodable & Decodable) methods for all models used, otherwise you will not automatically follow.

  last public class MyModel: Object {
@objc dynamic var Id: String = ""
@objc dynamic var Name: String = ""
were Favorites: List ?
Var Topics: List ?
}

last public class UserSubject: Object {
@objc dynamic var Id: String = ""
@objc dynamic var Name: String = ""
were teachers: List ? // f.e.
}

extension MyModel: Codable {
private enum MyModelCodingKeys: String, CodingKey {
case id
case name
case favorites
scissors topics
}

public convenience init (from decoder: decoder) throws {
self.init ()

let container = try dekoder.container (keyedBy: MyModelCodingKeys.self)

whose container.contains (.Id) {
self.Id = try container.decode (String.self, forKey: .Id)
}
whose container.contains (.Name) {
self.Name = try container.decode (String.self, forKey: .Name)
}
whose container.contains (.Favorites) {
la favorites = try container.decode (Array  .self, forKey: .Favorites)
self.Favorites? .append (objectsIn: favorites)
}
whose container.contains (.subjects) {
let topics = try container.decode (Array  .self, forKey: .Subjects)
self.Subjects? .append (objectsIn: subjects)
}
}

public func code (for encoder: encoder) throws {
was container = encoder.container (keyedBy: MyModelCodingKeys.self)
try container.encode (Id, forKey: .Id)
try container.encode (Name, forKey: .Name)
leave favorites: [String]? = Favorites? .CompactMap ({$ 0})
try container.encodeIfPresent (favorites, forKey: .Favorites)
let professionals: [UserSubject]? = Topics? .CompactMap ({$ 0})
try container.encodeIfPresent (topics, forKey: .Subjects)
}
}

extension UserSubject: Codable {
private enum MyModelCodingKeys: String, CodingKey {
case id
case name
case teachers
}

public convenience init (from decoder: decoder) throws {
self.init ()
let container = try dekoder.container (keyedBy: MyModelCodingKeys.self)
whose container.contains (.Id) {
self.Id = try container.decode (String.self, forKey: .Id)
}
whose container.contains (.Name) {
self.Name = try container.decode (String.self, forKey: .Name)
}
whose container.contains (.Teachers) {
let teachers = try container.decode (Array  .self, forKey: .Teachers)
self. Teachers? .append (objectsIn: teachers)
}
}

public func code (for encoder: encoder) throws {
was container = encoder.container (keyedBy: MyModelCodingKeys.self)
try container.encode (Id, forKey: .Id)
try container.encode (Name, forKey: .Name)
let teachers: [String]? = Teachers? .CompactMap ({$ 0})
try container.encodeIfPresent (teachers, forKey: .Teachers)
}
}


Source link