如何使用谓词从核心数据中获取偶数和奇数值 [英] How to fetch even and odd values from core data using Predicate
本文介绍了如何使用谓词从核心数据中获取偶数和奇数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从我的核心数据实体中获取偶数和奇数,请查看下面的代码并进行更正,因为它使应用程序崩溃。
I want to fetch even and odd values from my core data entity, please look into below code and correct, because its crashing the app.
NSPredicate *predicate;
if ([leadFilter.rank isEqualToString:@"Even"]) {
predicate = [NSPredicate predicateWithFormat:@"(street%2) = 0"];
}
else
predicate = [NSPredicate predicateWithFormat:@"street%2 != 0)"];
[predicateArray addObject:predicate];
是无法解析街道%2 = 0。
推荐答案
您可以直接在Core Data中执行此操作,但是语法有点麻烦。要仅获取 street
的值,请按以下步骤设置获取:
You can do this directly in Core Data, but the syntax is a little hairy. To fetch only values of street
that are even, set up your fetch like this:
NSExpression *evenOddExpression = [NSExpression expressionWithFormat:@"modulus:by:(%K,2)", @"street"];
NSFetchRequest *evenOddFetch = [NSFetchRequest fetchRequestWithEntityName:@"ENTITY_NAME"];
NSExpression *zeroExpression = [NSExpression expressionForConstantValue:@0];
NSPredicate *evenOnly = [NSComparisonPredicate predicateWithLeftExpression:evenOddExpression rightExpression:zeroExpression modifier:NSDirectPredicateModifier type:NSEqualToPredicateOperatorType options:0];
evenOddFetch.predicate = evenOnly;
结果将是具有 street均等值的任何托管对象
。
更新:在Marcus指出 NSDictionaryResultType
实际上并不需要。
Update: Made simpler after Marcus pointed out that NSDictionaryResultType
wasn't actually needed.
这篇关于如何使用谓词从核心数据中获取偶数和奇数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文