【问题标题】:Uncaught exception: *** -[__NSArrayM objectAtIndex:]: index 60 beyond bounds [0 .. 59]未捕获的异常:*** -[__NSArrayM objectAtIndex:]:索引 60 超出范围 [0 .. 59]
【发布时间】:2013-05-20 17:52:06
【问题描述】:
    NSLog(@"m_datasource %d and coord.color %d",[m_dataSource.colors count],[coord.colorIndexes count]);

            cell.spotColor  = [m_dataSource.colors objectAtIndex: [coord.colorIndexes lastObject] intValue];

这里是我得到的值 m_datasource 60 和 coord.color 2 如何解决这个问题?

【问题讨论】:

  • 呃,使用更大的数组或更小的索引。 (请注意,一个常见的错误是忘记数组索引运行 0..N-1 而不是 1..N。)
  • 您今天在这里遇到了同样的问题stackoverflow.com/questions/16648195/…。我不想听起来不友好,但是您了解问题和解决方案吗?

标签: iphone arrays exception


【解决方案1】:

是不是因为您的 NSArray(我假设您正在使用)从零开始?并且第 60 个对象在索引 59 处?

【讨论】:

  • NSLog(@"m_datasource %d and coord.color %d",[m_dataSource.colors count],[coord.colorIndexes count]); cell.spotColor = [m_dataSource.colors objectAtIndex:( [coord.colorIndexes lastObject] intValue]-1);
  • 试试看,最后有一个'-1'。如果这不起作用,请将您拥有的所有代码发送给我,我会对其进行排序
【解决方案2】:

如果您使用 count 方法并使用返回值来获取索引处的对象,那么您必须减去 1,因为 2 个对象的数组的计数为 2,但对象 1 的索引为 0 并且对象 2 的索引为 1。

int index = [someArraytoCount count] - 1;

someObj *myObj = [otherArray objectAtIndex:index];

另外通过使用逻辑是安全的。

if (index < [otherArray count] && index >= 0)

那么该索引将存在于数组中,您不会出现应用崩溃

【讨论】:

    【解决方案3】:

    你做错了:

    NSLog(@"m_datasource %d and coord.color %d",[m_dataSource.colors count],[coord.colorIndexes count]);
    cell.spotColor  = [m_dataSource.colors objectAtIndex: [coord.colorIndexes lastObject] intValue];
    

    如果您在coord.colorIndexes 中的最后一个对象是“100”,那么请检查 statemnt - 它看起来像这样:

    cell.spotColor  = [m_dataSource.colors objectAtIndex: 100]; 
    

    但是在您的 m_dataSource.colors 数组中仅包含 60 个对象,这就是它抛出数组超出索引异常的原因。

    用下面的sn-p替换你的代码:

    // get array count and substract with 1 - so it will retrun you last index of coord.colorIndexes array
    cell.spotColor  = [m_dataSource.colors objectAtIndex: [coord.colorIndexes count]-1];
    

    希望这将有助于您简要介绍数组概念。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多