Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSManagedObjectID into NSData

I found this wonderful NSManagedObjectID. This would be very good for referencing an Entity/NSManagedObject/NSEntityDescription, right?
Let's get an ID from an entity:

NSEntityDescription *entity = [self newEntity];     
NSManagedObjectID *objID = [entity objectID];

So... any idea how to get this objID into a string? Or better: NSData. Actually something to be able to save it to the NSUserDefaults. ;-)

Btw: NSFetchRequest doesn't want to work in my case. I use an modified version of this example: answer of an old question.

like image 408
papr Avatar asked Feb 05 '09 15:02

papr


2 Answers

To get an archived URI corresponding to a NSManagedObject's objectID:

NSManagedObject* myMO;
...
NSURL *uri = [[myMO objectID] URIRepresentation];
NSData *uriData = [NSKeyedArchiver archivedDataWithRootObject:uri];

In order to get back to an instance of the original managed object, you need a CoreData stack with the persistent store holding that instance already added to the NSPersistentStoreCoordinator. Then:

NSData *uriData;
NSPersistentStoreCoordinator *psc;
NSManagedObjectContext *moc; //with moc.persistentStoreCoordinator = psc.
...
NSURL *uri = [NSKeyedUnarchiver unarchiveObjectWithData:uriData];
NSManagedObjectID *moID = [psc managedObjectIDForURIRepresentation:uri];
NSManagedObject *myMO = [moc objectWithID:moID];
like image 163
Barry Wark Avatar answered Oct 06 '22 17:10

Barry Wark


From the NSManagedObjectID documentation:

Object IDs can be transformed into a URI representation which can be archived and recreated later to refer back to a given object (using managedObjectIDForURIRepresentation: (NSPersistentStoreCoordinator) and objectWithID: (NSManagedObjectContext). For example, the last selected group in an application could be stored in the user defaults through the group object’s ID. You can also use object ID URI representations to store “weak” relationships across persistent stores (where no hard join is possible).

Just turn it into a URL then turn that into a string or a data.

like image 25
Louis Gerbarg Avatar answered Oct 06 '22 17:10

Louis Gerbarg