How to fetch even and odd values from core data using Predicate

一曲冷凌霜 提交于 2020-01-13 20:28:50

问题


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];

Its saying unable to parse street%2=0.


回答1:


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;

The result will be whichever managed object have an even value of street.

Update: Made simpler after Marcus pointed out that NSDictionaryResultType wasn't actually needed.




回答2:


This kind of math in a predicate is not supported.

Workaround:

Create a boolean computed property isEven in the NSManagedObject subclass

- (BOOL)isEven
{
   return self.street % 2 == 0
}

and use the format isEven == TRUE or isEven == FALSE in the predicate.

predicate = [NSPredicate predicateWithFormat:@"isEven == TRUE)"];


来源:https://stackoverflow.com/questions/36605430/how-to-fetch-even-and-odd-values-from-core-data-using-predicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!