Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decodable CoreStoreObject subclass implementation #282

Closed
eraydiler opened this issue Oct 29, 2018 · 2 comments
Closed

Decodable CoreStoreObject subclass implementation #282

eraydiler opened this issue Oct 29, 2018 · 2 comments

Comments

@eraydiler
Copy link

eraydiler commented Oct 29, 2018

Hello,

I'm trying to figure out how to implement a CoreStoreObject subclass that also needs to conform to Decodable protocol. What I came up with is the code below.

`
class TestObject: CoreStoreObject, Decodable {
let title = Value.Optional("title", initial: nil)

 private enum CodingKeys: String, CodingKey {
     case title = "title"
 }

 required init(from decoder: Decoder) throws {
     let values = try decoder.container(keyedBy: CodingKeys.self)

     title.value = try values.decodeIfPresent(String.self, forKey: .title)

     super.init(asMeta: ())
 }

 required init(asMeta: Void) {
     super.init(asMeta: ())
 }

 required init(rawObject: NSManagedObject) {
     super.init(asMeta: ())
 }

}
`

However I'm having error;
❗ [CoreStore: Assertion Failure] Value.swift:373 value
↪︎ Attempted to access values from a 'Test' meta object. Meta objects are only used for querying keyPaths and infering types.

I think issue is related to the init(asMeta:...), init(rawObject:...) methods' implementation.
What is the proper way to implement these methods?
Thanks.

@JohnEstropia
Copy link
Owner

As mentioned somewhere in the discussion in mogenerator's prototype for Codable support, NSManagedObjects generally do not really play well with Encodable because the init(decoder:) needs to be implemented, while NSManagedObject's init(context:) needs an instance of the NSManagedObjectContext where the object will be added. (Basically you can call init(decoder:) many times without side effects, but init(context:) does)

You are hitting the same limitation with CoreStoreObject here, where it needs the context (via the NSManagedObject in init(rawObject:)).

You can borrow the techniques used in the mogenerator proposal above, but at that point I would recommend you to use ImportableUniqueObjects instead as they are much much more simple.

@eraydiler
Copy link
Author

I solved my issue by creating two different objects. They conform CoreStoreObject and Decodable seperately. Added additional methods to make required mapping between them. Thanks for the information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants