是否可以在 init() 之外使用 JSONDecoder() 来更新对象的属性?

Zig*_*yST 5 core-data ios swift codable

我正在使用 Codable 创建 NSManagedObjects,jsondecode.decode([User].self, from: jsonDataRaw) 但我的问题是 decode.decode() 每次都会创建一个新对象,但我需要一种方法来使用 jsonData 更新现有对象,而不是创建新对象。

有没有办法使用 Codable 做到这一点?

class User : NSManagedObject, Codable {
   required convenience init(from decoder: Decoder) throws {

        guard let contextUserInfoKey = CodingUserInfoKey.context,
            let managedObjectContext = decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
            let entity = NSEntityDescription.entity(forEntityName: MERUser.entityName, in: managedObjectContext) else {
                fatalError("Failed to decode")
        }
        self.init(entity: entity, insertInto: managedObjectContext)
        try update(with: decoder)
    }

    func update(with decoder: Decoder) throws {

        // Decode
        guard let values = try? decoder.container(keyedBy: CodingKeys.self) else {
                assertionFailure("no decoder")
                return
        }
        self.id = (try values.decode(Int64.self, forKey: .id))
        if let value = try? values.decodeIfPresent(Int64.self, forKey: .currentPoint),
            let unwrappedValue = value {
            self.currentPoint = unwrappedValue
        }
    }
Run Code Online (Sandbox Code Playgroud)

inr*_*on7 4

看起来你可以,但你需要卷起袖子一点。稳定内核有一篇关于如何解决这个问题的文章。

从简介:

尽管这些协议很有用,但它们缺少一项我发现在使用远程服务时非常常见的功能:从数据更新现有模型对象的能力。构建此功能是探索可编码协议和相关类型的一个很好的练习。

https://stablekernel.com/understanding-extending-swift-4-codable/