带有 NSPredicate 的 Fetchrequest 不返回正确的值

Posted

技术标签:

【中文标题】带有 NSPredicate 的 Fetchrequest 不返回正确的值【英文标题】:Fetchrequest with NSPredicate not returning right values 【发布时间】:2013-01-11 03:05:08 【问题描述】:

我在使用 Core Data 时遇到了一个奇怪的问题。 问题是我正在寻找属性小于 X 的对象,并且它没有返回所有匹配的值。 没有缓存,我没有使用 //[fetchRequest setFetchBatchSize:50];

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"self.level <= [cd] %@", [self.filters objectForKey:@"level"]];

我将它添加到谓词的 MutableArray 中,然后我执行 NSPredicate *myPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: subPredicates];

这是一个返回 myPredicate 的函数,称为 preparePredicates。目前没有更多的谓词,只有一个。 它的 NSLog 返回:level

NSError* error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"myEntity"
                                          inManagedObjectContext:self.context];
[fetchRequest setEntity:entity];
NSPredicate* predicate = [self preparePredicates]; 
[fetchRequest setPredicate:predicate];

//[fetchRequest setFetchBatchSize:50];
NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
NSLog (@"Error: %@", error);
NSLog(@"los fetchedobjects: %i",[fetchedObjects count]);
return fetchedObjects;

它不会返回任何错误。 如果我查看结果,没有一个级别为 6,但还有其他匹配(都低于指定的)。我知道有一个6级。 如果我在 SQLite 数据库浏览器中打开 .sqlite,我可以在那里看到它。 如果我用这个程序做一个

SELECT * FROM zmyentity WHERE zlevel <30; 

它不会出现,就像在 Core Data 中一样。但如果我做一个 SELECT * FROM zmyentity WHERE zlevel == 6; 它出现。 我真的不知道发生了什么。也许我犯了一个菜鸟错误,所以请指出我正确的方向。 非常感谢您。

【问题讨论】:

【参考方案1】:

可能您已将级别存储为 String 属性,因为

"30" < "6"

比较字符串时。选择数字属性类型(整数 16/32/64)应该可以解决问题。 myEntity 类中对应的 level 属性具有 NSNumber 类型。

您还应该在谓词中省略 [cd] 修饰符,因为这会强制进行字符串比较。

您的谓词可能如下所示:

[NSPredicate predicateWithFormat:@"self.level <= %d", [[self.filters objectForKey:@"level"] intValue]]

【讨论】:

非常感谢。确实是问题的根源。此外,使用 NSNumber 时,predicateWithFormat 必须与对象引用 %@ 一起才能正常工作,而不是加倍。 NSPredicate *pred = [NSPredicate predicateWithFormat:@"self.level @CarlosPastor:不客气。如果答案有帮助,请不要忘记通过单击复选标记大纲“接受”它,谢谢。 @CarlosPastor:你可以通过两种方式做到这一点:%@ 带有 NSNumber 对象,或 %d 带有整数参数,两者都可以。 - 我建议%d[[self.filters objectForKey:@"level"] intValue] 参数,因为我不知道“级别”是数字还是字符串。

以上是关于带有 NSPredicate 的 Fetchrequest 不返回正确的值的主要内容,如果未能解决你的问题,请参考以下文章

带有核心数据对象的 NSPredicate

带有嵌套数组的 NSPredicate

带有 NSPredicate 的 NSFetchedResultsController 未更新

带有 groupBy 的 nspredicate 不喜欢带有 nsdate 的谓词比较

带有 NSPredicate 的 NSFetchRequest 不返回任何结果

带有特殊字符的 NSPredicate 过滤