Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a JSONDecoder() outside the init() to update an object's attributes?

I'm creating NSManagedObjects using Codable's jsondecode.decode([User].self, from: jsonDataRaw) but my problem is that decode.decode() creates an new object every time , but instead I need a way to update exising objects with the jsonData rather than creating new ones.

Is there a way to do that using 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
        }
    }
like image 613
ZiggyST Avatar asked Jan 11 '18 15:01

ZiggyST


1 Answers

Looks like you can but you'll need to roll up your sleeves a little. Stable Kernel has an article on how to approach this.

From the intro:

As useful as these protocols are, they are missing one piece of functionality that I find is pretty common when working with remote services: the ability to update an existing model object from data. Building this functionality is a great exercise to get to explore the Codable protocols and related types.

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

like image 195
inreflection7 Avatar answered Sep 18 '22 17:09

inreflection7