LPPloveROU 2013-01-21 02:39 采纳率: 50%
浏览 3582
已采纳

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” 的对象索引呢?

  • 写回答

1条回答 默认 最新

  • Matt 2013-01-21 17:04
    关注

    这个可以通过设置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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置