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.
You don't need to convert the NSURL into an NSString before archiving. Just archive the NSURL.
Edit: I've recently learned that an object's ID can change, such as after a migration. It therefore seems like not a good idea to save an ID to disk expecting to be able to reference the object later.
As @preston said, don't save an objectID to disk, instead:
Much cleaner and better!
Did you look at URIRepresentation? It's easy to convert an NSURL to an NSString, and that to an NSData.
To get an archived URI corresponding to a
NSManagedObject
'sobjectID
: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:From the NSManagedObjectID documentation:
Just turn it into a URL then turn that into a string or a data.
Here's the cleanest and shortest way I've found to do this currently, using the setURL and getURL methods added in 4.0 to avoid extra calls to NSKeyedUnarchiver and NSKeyedArchiver:
Setter:
Getter: