[英]indexesOfObjectsPassingTest: | once indexes have been found how to check if if they are sequential?
I am using indexesOfObjectsPassingTest successfully to get the indexes that I require. 我正在成功使用indexsOfObjectsPassingTest来获取所需的索引。
With the found indexes I would like check if any of the indexes are sequential. 使用找到的索引,我想检查是否有任何索引是连续的。 If they are I would like to get the first in that sequence and the last in the sequence.
如果是的话,我想获得该序列中的第一个和序列中的最后一个。
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);
As an example the log produces 例如,日志生成
Domestic indexes: [number of indexes: 3 (in 2 ranges), indexes: (0 3-8)] 国内索引:[索引数:3(在2个范围内),索引:(0 3-8)]
With index 0 there is only 1 in sequence so I would like it returned. 索引为0时,序列中只有1个,因此我希望它返回。 With index 3-8 I would like to return 3 and 8
对于索引3-8,我想返回3和8
I can enumerate the indexes but an not sure how to check that the indexes are in sequence and to just get the indexes that are at the beginning and end of each sequence. 我可以枚举索引,但不确定如何检查索引是否按顺序排列,以及如何获取每个序列开头和结尾处的索引。
Let NSIndexSet
do the work for you. 让
NSIndexSet
为您完成工作。
For simplicity, this code constructs a second index set from the first, but it's easily adapted to do whatever you want. 为简单起见,此代码从第一个索引构建了第二个索引集,但可以轻松地对其进行修改以执行您想要的任何事情。
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);
The log at the end will print the 3 indexes: 0, 3, 8 最后的日志将打印3个索引:0、3、8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.