【问题标题】:Is it possible to use a JSONDecoder() outside the init() to update an object's attributes?是否可以在 init() 之外使用 JSONDecoder() 来更新对象的属性?
【发布时间】:2018-01-11 15:17:31
【问题描述】:

我正在使用 Codable 的 jsondecode.decode([User].self, from: jsonDataRaw) 创建 NSManagedObjects 但我的问题是 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
        }
    }

【问题讨论】:

  • 看来你已经开始研究update 函数了,这是怎么回事?
  • @DávidPásztor 我认为问题在于如何从init 以外的任何地方调用update。就像您从服务器 API 获得新的 JSON 并且想要就地更新现有对象而不是创建新实例一样。
  • @DávidPásztor,Tom Harrington 说的是对的,我找不到用解码器更新对象而不是创建新对象的方法。

标签: ios swift core-data codable


【解决方案1】:

看起来你可以,但你需要稍微卷起袖子。 Stable Kernel 有一篇文章介绍了如何解决这个问题。

从简介:

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

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

【讨论】:

    猜你喜欢
    • 2021-05-01
    • 2013-10-12
    • 2020-07-03
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2016-06-24
    相关资源
    最近更新 更多