cocoa - 使用 NSManagedObjectContext 的 objectWithID : 的 'proper' 方法是什么

标签 cocoa core-data nsmanagedobjectcontext

文档状态:

...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,然后使用请求的结果,并带有相应的注释:

 // 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 的结果 - 这意味着它的属性被访问并被愉快地处理。

是否应该将objectWithID始终视为“可能存在”对象?

我问这个问题是因为我刚刚遇到这个问题并且没有针对它的存在进行获取。

最佳答案

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

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

Here's Apple's documentation explaining faults (这就是 objectWithID: 返回给您的内容)。

关于cocoa - 使用 NSManagedObjectContext 的 objectWithID : 的 'proper' 方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4818526/

相关文章:

ios - 从 Web 下载图像并使用 Core Data 对其进行缓存

swift - NSManagedObject 不是故障,但应用程序在后台线程上访问它时崩溃

ios - 当管理对象上下文从持久性存储中加载数据时

cocoa - 如何实现 'NSTableview Delegate'方法?

swift - NSCollectionView sizeForItemAt 在尝试引用其集合中的项目时始终返回异常

ios - 通过 CoreData 属性显示 tableView 项目

iPhone iOS 如何合并 Core Data NSManagedObjectContext?

objective-c - 将其他正在运行的应用程序的窗口置于最前面

macOS/Cocoa/SwiftUI - 如何判断用户是否更喜欢左键单击作为辅助单击?

ios - 使用 swift : [SimpleRunner. 运行 setTime:] 时出现核心数据错误:无法识别的选择器发送到实例