views:

31

answers:

3

I have this code:

NSEntityDescription *userEntity = [[[engine managedObjectModel] entitiesByName] objectForKey:@"User"];
User *user = [[User alloc] initWithEntity:userEntity insertIntoManagedObjectContext:[engine managedObjectContext]];

and I want to know the id of the object inserted to the managed object context. How can i get that?

Will that id remain the same for that object's lifetime or will it persist to the sqlLite database beneath this and be something that can be used to uniquely identify it during a fetch operation (my ultimate goal).

Any help appreciated // :)

A: 

Read up on "managed object IDs" in the Core Data Programming Guide

You can get the object id from the object with something like:

NSManagedObjectID *moID = [managedObject objectID];
David Gelhar
A: 

First, you are constructing your objects in a non-preferred manner. Generally you should:

User *user = [NSEntityDescription insertEntityForName:@"User" intoManagedObjectContext:[engine managedObjectContext]];

Second, when you create the object it will get a temporary id which you can access via [user objectID] as David mentioned. Once you save the context then it will get a new "permanent" id.

However this id can and does change over the lifetime of the entity (although not the instance). Things like migrating the data can cause this id to change. However, between saving the context and exiting the application the id will remain the same.

Marcus S. Zarra
+1  A: 

If you want to save an object's ID permanently you need to:

  1. Save the object into the context so that the ID changes from a temporary to a permanent ID.
  2. Extract the URI version of the permanent ID with -[NSManagedObjectID URIRepresentation]. That returns a NSURL you can store as transformable attribute in another managed object.
  3. You can get the object by using -[NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:] to generate a new NSManagedObjectID object and then use -[NSManagedObjectContext objectWithID:] to get the actual referenced managed object.

The URI is supposed to identify a particular object in a particular store on a particular computer but it can change if you make any structural changes to the store such as migrating it to a new model version.

However, you probably don't need to do any of this. ObjectIDs play a much smaller role in Core Data than they do in other Data Model systems. Core Data maintains an object graph that uniquely identifies objects by their location in the graph. Simply walking the graph relationships takes you to a specific unique object.

The only time you really need ObjectID is when you're accessing object across two or more persistent stores. You need them then because relationships don't cross stores.

TechZen
Thanks, awesome answer! :)
Spanky