Core Data Primary Key

Your options are:

  • Use -[NSManagedObject objectID]. Note that this ID is temporary until either the object is saved for the first time or you call -[NSManagedObjectContext obtainPermanentIDsForObjects:error:]
  • Use the CFUUID family of functions to generate a UUID for each object in your -awakeFromInsert method
  • Create your own primary key-like system that stores an integer in your model and increments it with the creation of each object

There is no good way to validate that a property is unique. The closest you’ll get is to ensure it is unique at creation time, and then implement a custom setter method that stops anyone ever changing the ID.

Leave a Comment