使用NSManagedObjectContext的objectWithID的“正确”方法是什么: [英] what's the 'proper' way to use NSManagedObjectContext's objectWithID:

查看:84
本文介绍了使用NSManagedObjectContext的objectWithID的“正确”方法是什么:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档状态:


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

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

,在Apple的 Core Recipes示例应用程序中,该方法的结果用于填充NSFetchRequest,然后使用请求的结果,并带有注释效果:

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];

我看过很多例子(其他人的代码和苹果的 iClass),其中 objectWithID 是直接使用的-意思是,它的属性可以被访问和愉快地处理。

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.

应该 objectWithID 总是被视为也许存在对象?

Should objectWithID always be treated as a 'maybe-this-exists' object?

我问是因为我

推荐答案

Apple文档告诉您的内容不是假设存在该对象是持久性存储,只是因为返回了一个对象

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.

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

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.

这是Apple的文档,解释了错误 objectWithID:返回给您)。

这篇关于使用NSManagedObjectContext的objectWithID的“正确”方法是什么:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆