Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the 'proper' way to use NSManagedObjectContext's objectWithID:

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.

like image 655
lulu Avatar asked Jan 27 '11 15:01

lulu


2 Answers

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).

like image 60
paulbailey Avatar answered Nov 16 '22 11:11

paulbailey


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.

like image 23
Rob Glassey Avatar answered Nov 16 '22 11:11

Rob Glassey