我正在成功地使用indexesOfObjectsPassingTest来获取所需的索引。
对于找到的索引,我想检查是否有任何索引是连续的。如果是的话,我想得到序列中的第一个和序列中的最后一个。
NSMutableArray *domesticSetResult = [[NSMutableArray alloc]init];
domesticSetResult = nil;
NSMutableArray *matches = [NSMutableArray array];
NSIndexSet *domesticIndex = [self.days indexesOfObjectsPassingTest: ^(id obj, NSUInteger idx, BOOL *stop)
{
if ([obj isDomestic])
return YES; // found a match, keep going
else
return NO; // keep looking
} ];
[domesticIndex enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
[matches addObject:[self.days objectAtIndex:idx]];
}];
NSLog(@"\n\nDomestic indexes: %@\n\n", domesticIndex);作为一个例子,日志生成
国内指数:指数数:3(2个范围),指数:(0 3-8)
对于索引0,只有1的顺序,所以我希望它返回。对于索引3-8,我想返回3和8。
我可以枚举索引,但不确定如何检查索引是否按顺序排列,并只获取每个序列开头和结尾处的索引。
发布于 2016-03-13 07:29:55
让NSIndexSet为你做这件事。
为了简单起见,这段代码从第一个索引开始构造第二个索引集,但是它很容易被调整到您想做的任何事情。
NSMutableIndexSet *s = [NSMutableIndexSet indexSetWithIndex:0];
[s addIndex:3];
[s addIndex:4];
[s addIndex:5];
[s addIndex:6];
[s addIndex:7];
[s addIndex:8];
NSMutableIndexSet *s2 = [[NSMutableIndexSet alloc] init];
[s enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
NSLog(@"%@", NSStringFromRange(range));
[s2 addIndex:range.location];
if (range.length > 1) {
[s2 addIndex:range.location + range.length - 1];
}
}];
NSLog(@"%@", s2);最后的日志将打印3个索引: 0、3、8。
https://stackoverflow.com/questions/35966409
复制相似问题