Using @min,@max and etc inside a predicate?
Is it possible to use aggregate operator such as @min inside a predicate?
BTW The predicate filters an array of objects.
开发者_Go百科NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.score == @min.score"];
I know you can retrieve the min value using the key-value operators eg:
NSNumber *minScore = [myArray valueForKeyPath:@"@min.score"];
So far I only get errors about the objects not being key value compliant for "@min".
Thanks
The reason that you're getting that error is that the predicate is being applied to each object in myArray
, and those objects apparently don't support the key path @min.score
. NSPredicate does have support for at least some of the collection operators, though. Here's a simple example that works:
NSDictionary *d1 = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:35] forKey:@"score"];
NSDictionary *d2 = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:52] forKey:@"score"];
NSDictionary *d3 = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:13] forKey:@"score"];
NSDictionary *d4 = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:19] forKey:@"score"];
NSArray *array = [NSArray arrayWithObjects:d1, d2, d3, d4, nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.score == %@.@min.score", array];
NSLog(@"Min dictionaries: %@", [array filteredArrayUsingPredicate:predicate]);
You can see that in this case, the @min.score
key path is applied to the array, which makes sense. The output is an array containing the one dictionary that contains the minimum value:
Min dictionaries: (
{
score = 13;
}
)
精彩评论