什么是使用NSManagedObjectContext的objectWithID的"正确"方法:

lul*_*ulu 6 cocoa core-data nsmanagedobjectcontext

文档说明:

...此方法始终返回一个对象.假定objectID表示的持久性存储中的数据存在 - 如果不存在,则在访问任何属性时(即,触发错误时),返回的对象将引发异常.此行为的好处是它允许您创建和使用故障,然后在以后或在单独的上下文中创建基础行.

在Apple的'Core Recipes'示例应用程序中,该方法的结果用于填充NSFetchRequest,然后使用请求的结果,并对此结果进行注释:

 // 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];
Run Code Online (Sandbox Code Playgroud)

我已经看到很多例子(其他代码和apple的'iClass'),其结果来自objectWithID直接使用 - 意思是,它的属性被访问并快速处理.

应该objectWithID 始终被视为"可能存在"的对象吗?

我问,因为我刚刚遇到这个并没有反对它的存在.

pau*_*ley 4

苹果文档告诉你的是,不要仅仅因为返回了一个对象就假设该对象存在是持久性存储。

您可以像对待它一样对待它,访问其属性等等,因为在后台 Core Data 将访问数据存储来服务您的请求。但是,如果该对象在商店中不存在,您将收到异常。

这是解释故障的 Apple 文档(这是objectWithID:返回给您的内容)。