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
}
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With