iOS: Using @min and @max in a core data predicate

倖福魔咒の 提交于 2020-01-12 05:35:06

问题


I have a core data entity, Client, which has a discountproperty. I want to fetch the the client with the smallest discount.

I am using the following NSPredicate:

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

However, I am getting the following error:

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

What am not doing right?


回答1:


I don't think NSPredicate has support for functions like this unless it is part of a boolean predicate expression (i.e. involving things like "greater than").

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

There are a number of steps to follow to create and use the expression description.

First you need to create expressions (instances of NSExpression) to represent the key-path for the value you’re interested in, and to represent the function you want to apply (such as max: or min:):

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

For a full list of supported functions, see expressionForFunction:arguments:.

You then create the expression description and set its name, expression, and result type.

The name is the key that will be used in the dictionary for the return value. If you want to retrieve multiple values—such as the largest and the smallest salaries in an Employee table—the name of each expression description must be unique for a given fetch request.

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

Finally, you set the request’s properties to fetch just the property represented by the expression:

[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];


来源:https://stackoverflow.com/questions/10978010/ios-using-min-and-max-in-a-core-data-predicate

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