07-18-2023, 06:28 PM
Codable seems a very exciting feature. But I wonder how we can use it in Core Data? In particular, is it possible to directly encode/decode a JSON from/to a NSManagedObject?
I tried a very simple example:
[![enter image description here][1]][1]
and defined `Foo` myself:
import CoreData
@objc(Foo)
public class Foo: NSManagedObject, Codable {}
But when using it like this:
let json = """
{
"name": "foo",
"bars": [{
"name": "bar1",
}], [{
"name": "bar2"
}]
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let foo = try! decoder.decode(Foo.self, from: json)
print(foo)
The compiler failed with this errror:
super.init isn't called on all paths before returning from initializer
and the target file was the file that defined `Foo`
I guess I probably did it wrong, since I didn't even pass a `NSManagedObjectContext`, but I have no idea where to stick it.
Does Core Data support `Codable`?
[1]:
I tried a very simple example:
[![enter image description here][1]][1]
and defined `Foo` myself:
import CoreData
@objc(Foo)
public class Foo: NSManagedObject, Codable {}
But when using it like this:
let json = """
{
"name": "foo",
"bars": [{
"name": "bar1",
}], [{
"name": "bar2"
}]
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let foo = try! decoder.decode(Foo.self, from: json)
print(foo)
The compiler failed with this errror:
super.init isn't called on all paths before returning from initializer
and the target file was the file that defined `Foo`
I guess I probably did it wrong, since I didn't even pass a `NSManagedObjectContext`, but I have no idea where to stick it.
Does Core Data support `Codable`?
[1]: