I'm getting a response from an API and decoding the response like this:
struct MyStuff: Codable {
let name: String
let quantity: Int
let location: String
}
And I have instance an Entity to map MyStuff:
@objc(Stuff)
public class Stuff: NSManagedObject {
}
extension Stuff {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Stuff> {
return NSFetchRequest<Stuff>(entityName: "Stuff")
}
@NSManaged public var name: String?
@NSManaged public var quantity: Int64
@NSManaged public var location: String?
}
My question is, when I have the response of type MyStuff there is a way to loop thru the keys and map the values to core data?
for example:
let myStuff = MyStuff(name: "table", quantity: 1, location: "kitchen")
let myStuff = MyStuff(name: "table", quantity: 1, location: "kitchen")
for chidren in Mirror(reflecting: myStuff).children {
print(chidren.label)
print(chidren.value)
/*
insert values to core data
*/
}
I'll really appreciate your help
A smart solution is to adopt
DecodableinStuffWrite an extension of
CodingUserInfoKeyandJSONDecoderIn
StuffadoptDecodableand implementinit(from:), it must be implemented in the class, not in the extensionTo decode the JSON you have to initialize the decoder with the convenience initializer
where
contextis the currentNSManagedObjectContextinstance.Now you can create
Stuffinstances directly from the JSON.