Rob*_*Rob 5 iphone objective-c nspredicate
是否可以在谓词中使用@min等聚合运算符?
BTW谓词过滤对象数组.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.score == @min.score"];
Run Code Online (Sandbox Code Playgroud)
我知道你可以使用键值运算符检索最小值,例如:
NSNumber *minScore = [myArray valueForKeyPath:@"@min.score"];
Run Code Online (Sandbox Code Playgroud)
到目前为止,我只得到关于"@min"不符合键值的对象的错误.
谢谢
Cal*_*leb 13
您收到该错误的原因是谓词正在应用于每个对象myArray,并且这些对象显然不支持键路径@min.score.不过,NSPredicate确实支持至少一些收集运营商.这是一个有效的简单示例:
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]);
Run Code Online (Sandbox Code Playgroud)
您可以看到,在这种情况下,@min.score键路径应用于数组,这是有道理的.输出是一个包含一个包含最小值的字典的数组:
Min dictionaries: (
{
score = 13;
}
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8355 次 |
| 最近记录: |