核心数据NSPredicate“deleted == NO”不能按预期工作 [英] Core Data NSPredicate "deleted == NO" does not work as expected
问题描述
我使用UIManagedDocument与父子上下文。
I am using UIManagedDocument with Parent Child context.
在我的孩子上下文中,我执行以下操作:
In my child context I do the following
NSSet *results = [self.event.memberships filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return ([[evaluatedObject deleted] boolValue] == NO);
}]];
上述代码返回预期结果(仅限事件的未删除成员)。
Above code returns the expected results (only Not deleted members for the event).
但是这段代码没有。它获取所有记录。
But this code does not. It fetches all records.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"deleted == NO"];
NSSet *results = [self.event.memberships filteredSetUsingPredicate:predicate];
看起来很混乱。两者应该返回相同的结果,但 predicateWithBlock
返回正确的结果,其中 predicateWithFormat
返回所有记录。
It seems confusing. Both should return same results, but predicateWithBlock
returns correct results where as predicateWithFormat
returns all records.
使用 predicateWithBlock
而不是 predicateWithFormat
的利弊是什么? p>
What are the pros and cons of using predicateWithBlock
instead of predicateWithFormat
?
推荐答案
问题是你为你的实体定义了一个属性 deleted
与 NSManagedObject
的 isDeleted
方法冲突,因此您应重命名该属性。
The problem is that you have defined an attribute deleted
for your entity. That conflicts with the isDeleted
method of NSManagedObject
, so you should rename that attribute.
下面的实验显示,如果调用属性deleted( c
是一个自定义 deleted
属性):
The following "experiment" shows that strange things happen if you call your attribute "deleted" (c
is a managed object with a custom deleted
attribute):
// Set custom "deleted" property to YES:
c.deleted = @YES;
// Use the property, as your Code 1
NSLog(@"%@", [c deleted]);
// Output: 1
// Use Key-Value Coding, as your Code 2
NSLog(@"%@", [c valueForKey:@"deleted"]);
// Output: 0
// Now really delete the object and try again:
[context deleteObject:c];
NSLog(@"%@", [c valueForKey:@"deleted"]);
// Output: 1
您的代码1是指属性,因此返回预期结果。 代码2使用键值编码,并且 [c valueForKey:@deleted]
返回 YES
对象
实际上已从上下文中删除!
Your "Code 1" refers to the property, therefore it returns the expected result. "Code 2" uses Key-Value Coding, and [c valueForKey:@"deleted"]
returns YES
if the object
actually has been deleted from the context!
因此重命名该属性应该可以解决您的问题。不幸的是,如果属性名与内置方法冲突,编译器不会
发出警告。
So renaming that attribute should solve your problem. Unfortunately the compiler does not emit warnings if an attribute name conflicts with a built-in method.
这篇关于核心数据NSPredicate“deleted == NO”不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!