Core Data: Save unique object ID

10,330

Solution 1

I have a created date property in my object, so I just ended up using that date including seconds, which, seems to me like it will be unique and work how I want.

Solution 2

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.

Solution 3

You can create an id field for your object, and populate it during init using GUID. for how to create a GUID and optionally export it to string see UUID (GUID) Support in Cocoa

Share:
10,330
Nic Hubbard
Author by

Nic Hubbard

Updated on June 19, 2022

Comments

  • Nic Hubbard
    Nic Hubbard almost 2 years

    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?

  • d.lebedev
    d.lebedev over 12 years
    don't call object properties with names like 'id', 'description', etc.
  • Rambatino
    Rambatino over 9 years
    This to me seems like such a fudgey way of doing things. Saving it using a block and having a pointer to the original managedObjectContext and then setting the server side identification is so much neater.
  • Nicolas Miari
    Nicolas Miari about 8 years
    A possible problem that comes up to mind is, if multiple instances of your app happen to create objects at the exact same time (up to the second), and those objects are then uploaded to the server side, the IDs will collide. Otherwise, simple (even if a bit quick 'n' dirty)