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.