I need to have some unique&consistent ID for indexing data, I tried to use objectID of NSManagedObject, but looks like for the same entity, its objectID keeps changing, does anyone know if this is not consistent?
1 Answers
Unless you haven't saved a new object, the objectID is unique and consistent.
To quote the Core Data Programming Guide:
Managed Object IDs and URIs
An NSManagedObjectID object is a universal identifier for a managed object, and provides basis for uniquing in the Core Data Framework. A managed object ID uniquely identifies the same managed object both between managed object contexts in a single application, and in multiple applications (as in distributed systems). Like the primary key in the database, an identifier contains the information needed to exactly describe an object in a persistent store, although the detailed information is not exposed. The framework completely encapsulates the “external” information and presents a clean object oriented interface.
NSManagedObjectID *moID = [managedObject objectID];
There are two forms of an object ID. When a managed object is first created, Core Data assigns it a temporary ID; only if it is saved to a persistent store does Core Data assign a managed object a permanent ID. You can readily discover whether an ID is temporary:
BOOL isTemporary = [[managedObject objectID] isTemporaryID];
-
1"only if it is saved to a persistent store", does it mean after [context save] rather than after the entity is created? – hzxu May 31 '12 at 04:21
-
Yes, as svena says, it is after [context save] that it is assigned so permanent object id. – lnafziger May 31 '12 at 13:02
-
Would you maybe mind clarifying this a bit. If I want to store my data in a SQL database, for example. If I create objects on two different devices, can I make it so they have the same objectID? In other words if I want to create a syncing engine is objectID the right 'unique' identifier? I actually wrote my own personal ID which uses the object class + a timestamp. It's not great but it gets the job done. Would be nice to have a more core / system level ID though. – nazbot Jun 08 '13 at 00:29
-
1@nazbot: No, the unique object ID is ONLY unique for this object on this device. If you have two different devices, they will have different object ID's (even if all properties are the same). – lnafziger Jun 08 '13 at 02:05
-
@nazbot: I had the same requirement. I created a new string field for each record called uuid, and made it required. This way it's not controlled by CoreData, and allows me bind a UUID to each record. – stephen Jun 11 '13 at 18:49