Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ID of an object saved to Core Data's managed object context?

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 // :)

like image 410
Spanky Avatar asked Jul 15 '10 00:07

Spanky


2 Answers

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.

like image 114
TechZen Avatar answered Oct 26 '22 21:10

TechZen


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];
like image 24
David Gelhar Avatar answered Oct 26 '22 19:10

David Gelhar