title: Using a dirty flag with Core Data for synchronizing with a server
body: <p>I am working on syncing data between the client and a server. I am using <code>MagicalRecord</code> (a Core Data wrapper) for storing the data on the client. I have an entity called <code>Dirty</code> that contains a single attribute called <code>dirty</code>. This represents if there were changes on the client that have not been pushed up to the server yet. <code>dirty</code> gets set to <code>[NSDate date]</code> anytime an attribute is set on the class (of course, when setting <code>dirty</code>, the correct value is set). Every other entity created on the client inherits from <code>Dirty</code>. The idea is that we won’t fetch new data from the server until all client data has been pushed up (only fetch new data if all entities have <code>dirty == nil</code>).</p>
  
  <p>When importing data from the server (using <code>+[NSManagedObject MR_importFromObject:inContext:</code>), each entity’s <code>dirty</code> attribute gets set to <code>nil</code> (because the client is up-to-date with the server). </p>
  
  <p>Right before a save is kicked off (inside the <code>+[MagicalRecord saveWithBlock:completion:]</code> save block), <code>dirty</code> is still <code>nil</code>. However, in the completion block, fetching the entity that was just saved (on the main thread) has a value for <code>dirty</code>. </p>
  
  <p>During the save, the entity is transferred to the main thread’s context. However, there is a problem because <code>-[NSManagedObject didChangeValueForKey:]</code> gets called for every attribute that is transferred from the <code>localContext</code> (background thread) to the main context (on the main thread). <code>dirty</code> gets set with <code>[NSDate date]</code> for each entity. Most of the time, <code>dirty</code> does not get set last, which means when another attribute is set, <code>dirty</code> is overwritten. </p>
  
  <p>Is there a way to make sure <code>dirty</code> is the last attribute that is set when transferring the NSManagedObject instance to the main thread’s context? I’m even willing to set <code>dirty</code> when the object is saved (instead of when the properties are set).</p>
  
  <p>I’ve tried all sorts of options, including checking against <code>-[NSManagedObject isInserted]</code> and <code>-[NSManagedObject isUpdated]</code> inside <code>-[NSManagedObject didChangeValueForKey:]</code>. One other thing that is kind of annoying is that the new object is inserted before the attributes are transferred over (I thought I could have some sort of flag to lock/unlock setting <code>dirty</code>).</p>
  
  <p>Another thing to note is <code>[NSManagedObject(_NSInternalMethods) _updateFromRefreshSnapshot:includingTransients:]</code> is what gets called right before <code>-[NSManagedObject didChangeValueForKey:]</code> is called on the new object.</p>
  
  <p>Any ideas? I’ve been facepalming over this for a couple days now.</p>