What is the β€œright” way to use NSManagedObjectContext objectWithID:

state of documents:

... This method always returns an object. Data in persistent storage represented by objectID is supposed to exist - if it is not, the returned object throws an exception when you access any property (that is, when an error is triggered). The advantage of this behavior is that it allows you to create and use errors, and then create the baseline later or in a separate context.

and in the Apple Core Recipes sample application, the result of the method is used to populate NSFetchRequest, and then the result of the request with comments on this effect is used:

// 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 saw many examples (other code and apple 'iClass'), where the result from objectWithID used directly - this means that its properties are available and processed together.

Should objectWithID always be considered as a possibly-this-existing object?

I ask because I just ran into this and was not going to exist.

+5
cocoa core-data nsmanagedobjectcontext
Jan 27 '11 at 15:49
source share
2 answers

In the Apple documentation, you should not assume that the object exists, it is persistent storage, just because the object is being returned .

You can treat it as if it did, access to its properties, etc., because in the background Core Data will access the data store to serve your request. However, if the object does not exist in the repository, you will get an exception.

Here's the Apple documentation explaining the errors (this is what objectWithID: gets back to you).

+4
Jan 29 '11 at 12:42 on
source share

I found this article Safely Obtaining NSManagedObject by URI to contain a good all in one method for capturing an object using objectWithID: but if it detects an error, go ahead and get it. A detailed method is discussed in detail in the work with object URIs, but the main technique presented is a useful continuation of the discussion in this matter.

+1
Jun 03 '13 at 9:45
source share



All Articles