Core Data Object IDs can change

I thought I knew a lot about Core Data with having used it a lot over the past years.  Today, I learned something new that I feel like I should have known for a long time.  NSManagedObjectIDs can change.  Seriously.

Identity in Core Data is really a tuple of (file aka store UUID, entity name, primary key). This can be captured in the -URIRepresentation from NSManagedObjectID. However, that requires using the same file, and not resetting the primary keys (e.g. changing the store UUID, or delete the file and creating a new one, or performing a not-light-weight migration)

If you want a different notion of identity, you can just add an UUID string as an attribute to your entity. A separate mapping table is not recommend. The 2 apps should agree to use the same UUIDs for the same identities.

– Ben

Ref: https://devforums.apple.com/message/480640#480640

Ben is one of the core developers of Core Data at Apple.  The last sentence describing ways primary keys can change blew my mind when mentioning “not-light-weight migration”.  In WordPress for iOS we sometimes have to perform heavyweight migrations – especially in the case of removing objects or combining object ancestries.  In a number of cases we use NSManagedObjectID’s URIRepresentation and throw it in NSUserDefaults for retrieval later.  Turns out, that ID isn’t stable enough between migrations.

The solution, as Ben points out, is to create a UUID and make the ID yourself upon initial persistence.

Mind blown.

One thought on “Core Data Object IDs can change

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s