问题
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