Core Data: Save unique object ID
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
Nic Hubbard
Updated on June 19, 2022Comments
-
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 over 12 yearsdon't call object properties with names like 'id', 'description', etc.
-
Rambatino over 9 yearsThis 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 about 8 yearsA 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)