How to check existence of reference to an NSManagedObject?
-
22-09-2019 - |
Question
I successfully stored and retrieved a reference to an NSManagedObject using the example found in this site http://cocoawithlove.com/2008/08/safely-fetching-nsmanagedobject-by-uri.html
The problem is, the app crash whene triying to retrieve an NSManagedObject which has been deleted.
I tried the method isFault on the object, but it always returns no, even if the object IS there.
Here is my code I use to retrieve it:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *myData = [prefs objectForKey:@"activatedObject"];
if (myData)
{
NSURL *myURL = [NSKeyedUnarchiver unarchiveObjectWithData:myData];
NSManagedObjectID *myID = [self.persistentStoreCoordinator managedObjectIDForURIRepresentation:myURL];
id myObject = [self.managedObjectContext objectWithID:myID];
self.Object = myObject;
}
Solution
You can try call this method:
NSError *error = nil;
id myObject = [self.managedObjectContext existingObjectWithID:myID error:&error];
If object specified by myID cannot be fetched, or does not exist, or cannot be faulted, it returns nil.
OTHER TIPS
The docs mention that the object must be saved to the store before getting the objectID. Are you getting it before saving the store?
Also, just consider saving the value of a unique property of the the object and just perform a search instead.