如何使用Predicate从核心数据中获取偶数和奇数值

Arv*_*dar 2 core-data nspredicate ios

我想从我的核心数据实体中获取偶数和奇数值,请查看下面的代码并更正,因为它崩溃了应用程序.

        NSPredicate *predicate;
        if ([leadFilter.rank isEqualToString:@"Even"]) {
            predicate = [NSPredicate predicateWithFormat:@"(street%2) = 0"];
        }
        else
            predicate = [NSPredicate predicateWithFormat:@"street%2 != 0)"];
        [predicateArray addObject:predicate];
Run Code Online (Sandbox Code Playgroud)

它的说法无法解析街道%2 = 0.

Tom*_*ton 8

您可以直接在Core Data中执行此操作,但语法有点毛茸茸.要仅获取均值street,请按以下方式设置您的提取:

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;
Run Code Online (Sandbox Code Playgroud)

结果将是任何一个具有偶数值的托管对象street.

更新:马库斯指出NSDictionaryResultType实际上并不需要更简单.