IOS: using @min and @max in the main data predicate

I have a main data object, Client , which has a discount property. I want to get the customer with the lowest discount.

I am using the following NSPredicate :

 [NSPredicate predicateWithFormat:@"@min.discount"]; 

However, I get the following error:

 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "@min.discount"' 

That does not work?

+6
source share
1 answer

I don’t think NSPredicate has support for such functions unless it is part of a logical predicate expression (ie includes things like β€œmore”).

You should read this CoreData documentation , which provides some examples, specifically using max as an example:

There are a number of steps for creating and using the Description expression.

First you need to create expressions ( NSExpression instances) to represent the key path for the value you are interested in and represent the function you want to apply (for example, max: or min :):

 NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"salary"]; NSExpression *maxSalaryExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]]; 

For a complete list of supported functions, see expressionForFunction:arguments:

Then you create a description of the expression and specify its name, expression and type of result.

The name is the key that will be used in the dictionary for the return value. If you want to get multiple values ​​- for example, the largest and lowest salaries in the Employee table - the name of each description description must be unique for a given query query.

 NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init]; [expressionDescription setName:@"maxSalary"]; [expressionDescription setExpression:maxSalaryExpression]; [expressionDescription setExpressionResultType:NSDecimalAttributeType]; 

Finally, you set query properties to retrieve only the property represented by the expression:

 [request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]]; 
+7
source

Source: https://habr.com/ru/post/917776/


All Articles