Alex Rivera | Logout

Core Data primary key ID for a row in the database

Asked 2011-01-18T03:19:44.847
52

Suppose I have a list of books stored in Core Data. I want to search for a book by it's primary key ID.

I know the sqlite file created by Core Data has an ID column in each table, but this doesn't seem to be exposed to me in anyway.

Does anyone have any recommendations?

Edit
Report

1 Answer

47

As Barry Wark said, remember always that Core Data is not an orm. Pure SQL details are not exposed to the user and every row is just an object. By the way, sometime you should need to access the "primary key", for example when you need to sync the coredata db with external sql databases (in my case I needed it in a callback function to change the state of an object after INSERT it with success in the remote db). In this case, you can use:

objectId = [[[myCoredataObject objectID] URIRepresentation] absoluteString]

that will return a string like: x-coredata://76BA122F-0BF5-4D9D-AE3F-BD321271B004/Object/p521 that is the unique id used by Core Data to identify that object.

If you want to get back an object with that unique id:

NSManagedObject *managedObject = [managedObjectContext objectWithID:[persistentStoreCoordinator managedObjectIDForURIRepresentation:[NSURL URLWithString:objectId]]];

NB: Remember that if the receiver has not yet been saved in the CoreData Context, the object ID is a temporary value that will change when the object is saved.

answered 2011-07-04T08:18:05.470

Your Answer