我在 MacOsX 10.6 上使用 SQL 存储时遇到了 CoreData 的奇怪问题。我有一个NSManagedObject
子类名为 Family
具有属性 name
和关系personList
连接到另一个NSManagedObject
子类名为 Person
具有属性 firstname
和反比关系family
。一个Person
只有一个 family
,以及 family
可以有几个Person
s。
假设我有一个Family
对象family
指向“Doe”家庭 2 Person
(约翰和简)连接到它,我执行以下请求:
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:managedObjectContext]];
[request setPredicate:[NSPredicate predicateWithFormat:@"family.name=%@",[family name]]];
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
我得到一个大小为 2 的数组,其中有 2 个人:Jane 和 John,姓氏 Doe。现在,如果我使用其合成访问器更新该系列,在我的例子中:
[family setName:@"Wheat"]
获取Person
的列表后我无法使用相同的获取请求。结果是[array count]
的0
.
如果我将谓词更改为以下行,它会再次起作用:
[request setPredicate:[NSPredicate predicateWithFormat:@"family=%@",family]];
因此,就好像谓词没有使用系列属性名称的更新版本,即使我有 NSFetchRequest
设置为默认值(因此 includesPendingChanges
返回 YES)。这对我来说毫无意义。看来NSFetchRequest
找到 family
对象,但看不到它的值 family.name
已更新,未保存,位于 managedObjectContext
在内存中。当然,如果我保存商店,它就会再次起作用。
有什么想法吗?我已经阅读了 Mac 文档,但不明白为什么会失败。
最佳答案
我认为这里的关键是理解获取请求。它从持久存储中检索数据,因此很明显,如果您没有保存到持久存储中,它就不会找到该数据。如果您考虑到这一点,您所描述的情况是完全合乎逻辑的。
来自核心数据编程指南:
You cannot fetch using a predicate based on transient properties (although you can use transient properties to filter in memory yourself). Moreover, there are some interactions between fetching and the type of store—for details, see “Store Types and Behaviors.” To summarize, though, if you execute a fetch directly, you should typically not add Objective-C-based predicates or sort descriptors to the fetch request. Instead you should apply these to the results of the fetch. If you use an array controller, you may need to subclass NSArrayController so you can have it not pass the sort descriptors to the persistent store and instead do the sorting after your data has been fetched.
关于sql - NSFetchRequest 未捕获属性已更改的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7128211/