Search code examples
ioscore-datansmanagedobjectnsmanagedobjectcontext

Keeping a NSManagedObject up to date while retaining it


I have a NSManagedObject instance that represents a user in my application. I am retaining this instance and passing it between view controllers for the interface to reference. The managed object context (MOC) the user instance belongs to is a main queue MOC that is a child of a private queue MOC that saves directly to the persistent store.

My core data persistent store is updated in the background on a separate background queue. These updates are saved to a private queue MOC that is then committed to the main private queue MOC and subsequently saved to the persistent store.

My question is, how can I be sure that the user NSManagedObject instance will stay up to date? I'm aware of the existence of refreshObject:mergeChanges:, however, it seems complex to set up a of NSManagedObjectContextDidSaveNotification observers to simply keep an object instance up to date. I can see this approach becoming unruly when trying to keep multiple NSManagedObject instances up to date.


Solution

  • From experience, your best option is don't try to keep it up to date. You need to use implement the NSManagedObjectContextDidSaveNotification to keep your context up to date -- you can't get around that -- but to get a valid object, you'll need to re-query it after every update. The easiest approach to that will be application-dependent, but I frequently use unique, server-generated ID's to pass objects around, then fetch them out of the database using those when I need to use them. (The unique ID's are necessary because I'm generally consuming an API that uses them, so your results will vary) The only place where that technique may or may not work is where you're generating data locally, and haven't (yet) uploaded it to the database where it get's it's permanent ID. I generally special-case those and have a device ID separate from the 'real' ID, just to keep track of them until they get their real ID. Anything that doesn't have a 'real' ID is something my logic is aware of as something that needs to be persisted to server, so that works for me.