我正在使用jsonSerialization通过api检索Web数据。
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &e];
然后我能够使用以下谓词获得所需的数据。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"value == 1 && day = 0"];
NSArray *filteredArray = [[jsonArray filteredArrayUsingPredicate:predicate] valueForKey:@"hour"];
这给了我一个我想要的数据的过滤数组。
filteredArray = ( 0, 1, 2, 7, 8, 9, 14, 15, 16, 17 (
从这个filteredArray中,我需要提取所有连续数字的开头和结尾。例如,在上面的数组中,它们是(0, 2, 7, 9, 14, 18(。我正在尝试通过传递数组索引作为条件来在我的 filteredArray 上使用第二个谓词来实现这一点。
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"if (filteredArray[1] - filteredArray[0] !=0)"];
这让我的程序崩溃了。我以为我可以以这种方式将数组索引传递给谓词?
NSPredicate
是过滤范围的错误的API。
我建议将索引转换为NSIndexSet
并枚举范围
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSNumber *index in filteredArray) {
[indexSet addIndex:index.unsignedIntegerValue];
}
[indexSet enumerateRangesUsingBlock:^(NSRange range, BOOL * _Nonnull stop) {
NSLog(@"%ld, %ld", range.location, range.length);
}];