gonzalezreal / Groot

From JSON to Core Data and back.
Other
534 stars 61 forks source link

Ability to modify objects after being imported using Groot #93

Open ManueGE opened 5 years ago

ManueGE commented 5 years ago

Hello!

After using Groot for years I found a small improvement. Could we add a way to modify an object after it is parsed with Groot? Let me explain.

Let's say I have these entities:

User
    - id
    - name
    - role

Role
   - id
   - name
   - importedFromServer

Department
   - id
   - name
   - users

I would like to set the importedFromServer to true after every Groot import. I know that currently I can do it this way:

let role: Role = try object(fromJSONDictionary: dictionary, inContext: context)
role.importedFromServer = true

This is quite easy, but it the thing I import is a user, I need to do:

let user: User = try object(fromJSONDictionary: dictionary, inContext: context)
user.role.importedFromServer = true

And if I import a Department:

let department: Department = try object(fromJSONDictionary: dictionary, inContext: context)
department.users.forEach { $0.role.importedFromServer = true }

NOTE: This is just a silly example. Indeed I know I could do achieve this just by adding an entity transformer and adding the importedFromServer key to the entity dictionary. But again, this is just an example, what I want to actually achieve is not doable this way.

It would be great if we can do it in a single place.

My proposal for doing it is creating a NSManagedObject extension with a single empty method:

- (void) grt_awakeFromImport:(NSDictionary *) dictionary {
}

and call it after an object is inserted.

This way any NSManagedObject subclass can override this method and do their own stuff there. In our example, we can add this method to Role:

- (void) grt_awakeFromImport:(NSDictionary *) dictionary {
    self.importedFromServer = YES;
}

I can prepare a PR if you are willing to approve this feature.

Let me know your thoughts.

Thanks.

ManueGE commented 5 years ago

Interesting, I saw that we already discussed this 3 years ago: #48

I had forgotten the category I mentioned there, anyway I think that it is something useful for the project.

ManueGE commented 5 years ago

Just for clarification, let me explain a real-world use case of this.

In my app, my entities have a few computed var that is calculated once and cached. On each update, I want to clean up the cache, so those properties are calculated again. With this solution, I could do it easily, instead of calling cleanCache every time I complete an update operation.