the docs state:
...This method always returns an object. The data in the persistent store represented by objectID is assumed to exist—if it does not, the returned object throws an exception when you access any property (that is, when the fault is fired). The benefit of this behavior is that it allows you to create and use faults, then create the underlying rows later or in a separate context.
and in Apple's 'Core Recipes' sample app the result of the method is used to populate an NSFetchRequest, and the request's result is then used, with comments to that effect:
// first get the object into the context
Recipe *recipeFault = (Recipe *)[context objectWithID:objectID];
// this only creates a fault, which may NOT resolve to an object (for example, if the ID is for
// an objec that has been deleted already): create a fetch request to get the object for real
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity: [NSEntityDescription entityForName:@"Recipe" inManagedObjectContext:context]];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(self == %@)", recipeFault];
[request setPredicate: predicate];
I have seen many examples (other's code, and apple's 'iClass') where the result from objectWithID
is used directly - meaning, its properties are accessed and merrily processed along.
Should objectWithID
always be treated as a 'maybe-this-exists' object?
I'm asking because I've just run into this and hadn't been fetching against its existence.
What the Apple documentation is telling you is not to assume that the object exists is the persistent store, just because an object is returned.
You can treat it as though it does, accessing its properties and so on, because in the background Core Data will access the data store to service your request. However, if the object doesn't exist in the store, you'll get an exception.
Here's Apple's documentation explaining faults (which is what objectWithID:
is returning to you).
I found this article Safely fetching an NSManagedObject by URI to contain a nice all in one method for grabbing an object using objectWithID:
but if it's found to be a fault, to go ahead and fetch it. The method detailed goes a bit further in dealing with object URIs, but the core technique presented is a useful extension to the discussion in this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With