使用 NSPredicate 过滤,用于数组内部字典中数组的数组计数
Filtering with NSPredicate, for array count of Array inside dictionary inside array
我有如下格式的数组
[
{
"xyz" : [Array with different values];
... many more keys
},
{
.. same as above dictionary
}
... many more dictionaries
]
看这里,我有字典的主数组,其中每个字典都有不同的键,其中有 "xyz" 键,其值又是一个数组。现在我想要那些字典,其中 xyz 的数组必须有 count>2.
现在我尝试使用以下谓词:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.count>2"];
NSArray *filteredArray = [resultArray filteredArrayUsingPredicate:predicate];
但这给了我这样的错误,xyz is not key-value complaint for key "count"
在这种情况下,导致 -valueForKey: @"count"
被发送到每个 xyz 实例,而 xyz 的键值编码不符合计数。
相反,使用 @count
运算符计算集合的计数,然后使用
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.@count>2"];
而不是
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.count>2"];
在 Swift 3.0 中:
let fileterdArray = resultArray.filtered(using: NSPredicate.init(format: "xyz.@count>%d", 2))
我有如下格式的数组
[
{
"xyz" : [Array with different values];
... many more keys
},
{
.. same as above dictionary
}
... many more dictionaries
]
看这里,我有字典的主数组,其中每个字典都有不同的键,其中有 "xyz" 键,其值又是一个数组。现在我想要那些字典,其中 xyz 的数组必须有 count>2.
现在我尝试使用以下谓词:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.count>2"];
NSArray *filteredArray = [resultArray filteredArrayUsingPredicate:predicate];
但这给了我这样的错误,xyz is not key-value complaint for key "count"
在这种情况下,导致 -valueForKey: @"count"
被发送到每个 xyz 实例,而 xyz 的键值编码不符合计数。
相反,使用 @count
运算符计算集合的计数,然后使用
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.@count>2"];
而不是
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.count>2"];
在 Swift 3.0 中:
let fileterdArray = resultArray.filtered(using: NSPredicate.init(format: "xyz.@count>%d", 2))