Creating a unique id for a Core Data program on the iPhone

前端 未结 9 1562
暖寄归人
暖寄归人 2020-12-04 07:28

I am having a bit of trouble figuring out this Core Data stuff. How do I create a new entry with a unique ID? In SQL I would just declare one field as an autoincrement fie

9条回答
  •  醉酒成梦
    2020-12-04 08:03

    Here are three kinds of unique ID representation of CoreData object:

    NSManagedObjectID *taskID = [task objectID];
    NSURL *taskUniqueURLKey = task.objectID.URIRepresentation;
    NSString *taskUniqueStringKey = task.objectID.URIRepresentation.absoluteString;
    

    !!!!Note: if you want to use above unique key as index, please make sure the object is saved to context before using it , or the objectID would be a temporary Id, which will be replaced later (e.g. after saved). See the apple document of NSManagedObjectID class :

    - (BOOL)isTemporaryID;    // indicates whether or not this ID will be replaced later, 
    such as after a save operation (temporary IDs are assigned to newly inserted objects 
    and replaced with permanent IDs when an object is written to a persistent store); most
     IDs return NO
    

提交回复
热议问题