NSMutableArray对象的索引

NSMutableArray 中的对象是这样: “0,1,0,1,1,1,0,0”

然后我要获取所有值为“ 1 ”的对象的索引。

for (NSString *substr in activeItems){
            if ([substr isEqualToString:@"1"]){
                NSLog(@"%u",[activeItems indexOfObject:substr]);   
            }
    }

但是根据文档说明中方法indexOfObject是返回最低索引值,那么我应该怎么获取值为 “1” 的对象索引呢?

这个可以通过设置range来解决.

NSRange range = NSMakeRange(0, activeItems.count);
for (NSString *substr in activeItems)
{
    if ([substr isEqualToString:@"1"])
    {
        NSInteger index = [activeItems indexOfObject:substr inRange:range];
        NSLog(@"the object indix is: %d", index);
        range.location = ++index;
        range.length = activeItems.count - index;
    }
}

当然,这种对collection的过滤操作,我建议用NSPredicate.不过你这个过滤也不算复杂,怎样都行.
不过我还是给你写出来方法.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '1'"];
NSArray *resAry = [activeItems filteredArrayUsingPredicate:predicate];
NSRange range = NSMakeRange(0, activeItems.count);

for (NSString *substr in resAry)
{
    NSInteger index = [activeItems indexOfObject:substr inRange:range];
    NSLog(@"the object indix is: %d", index);
    range.location = ++index;
    range.length = activeItems.count - index;
}