Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: Save unique object ID

I see that there is a method of getting the unique id of a managed object:

NSManagedObjectID *moID = [managedObject objectID];

But, as I have read, that changes when it is saved.

What is a better way of creating my own unique ID and saving it in each object, making sure that it IS unique and does't change?

like image 955
Nic Hubbard Avatar asked Sep 19 '11 00:09

Nic Hubbard


1 Answers

You cannot save the NSManagedObjectID in a CoreData entity, and there's no properties in it that can be intended as integer or string ID. Therefore building your own unique identifier algorithm is an acceptable solution, if it's impossible for you to keep track when the entity is saved, I did this for some applications.

For example I had a similiar problem time ago, when I needed to fill a UITableView cells with a reference to the entity, and retrieve the entity after clicking/touching the cell.

I found a suggestion by using the uri representation, but however I still needed to save the context before, but I manage to use the NSFetchedResultsController and found a more solid solution rather than an application built id.

[[myManagedObject objectID] URIRepresentation];

Then you can later retrieve the managed object id itself:

NSManagedObjectID* moid = [storeCoordinator managedObjectIDForURIRepresentation:[[myManagedObject objectID] URIRepresentation]];

And with the moid I could retrieve your managed object.

like image 54
Leonardo Avatar answered Sep 29 '22 10:09

Leonardo