Master Data: Saving a Unique Object Identifier

I see that there is a method for obtaining a unique identifier for a managed object:

NSManagedObjectID *moID = [managedObject objectID]; 

But, as I read, this changes when you save it.

What is the best way to create your own unique identifier and store it in each object, making sure that it is unique and does not change?

+4
source share
4 answers

I have a date date property in my object, so I just ended up using this date, including seconds, which seems to me to be unique and work the way I want.

+6
source

You cannot store NSManagedObjectID in a CoreData object, and it does not have any properties that can be defined as integer or string identifiers. Therefore, creating your own unique identifier algorithm is an acceptable solution, if you can’t keep track of when the object is saved, I did this for some applications.

For example, I had a similar problem when I needed to populate UITableView cells with an object reference and get the object after clicking / touching the cell.

I found a suggestion using the uri view, but , but I still need to save the context until , but I manage to use the NSFetchedResultsController and find a stronger solution, rather than the built-in application identifier.

 [[myManagedObject objectID] URIRepresentation]; 

Then you can later get the identifier of the managed entity:

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

And with moid, I could get your managed entity.

+12
source

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

+3
source

If this helps someone else find this, here's how I do it:

Create an Object ID Property

Get the last used identifier when creating the object using this code:

 Playlist *latest; // Define entity to use and set up fetch request NSEntityDescription *entity = [NSEntityDescription entityForName:@"Playlist" inManagedObjectContext:managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entity]; // Define sorting NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"listID" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; // Fetch records and handle errors NSError *error; NSArray *fetchResults = [managedObjectContext executeFetchRequest:request error:&error]; if (!fetchResults) { NSLog(@"ERROR IN FETCHING"); } if ([fetchResults count] == 0) { latestID = 0; } else { latest = [fetchResults objectAtIndex:0]; latestID = latest.listID; } 

Set this to one on a new object.

+1
source

All Articles