未捕获的异常:*** - [__ NSArrayM objectAtIndex:]:索引60超出界限[0 .. 59]

时间:2013-05-20 17:52:06

标签: iphone arrays exception

    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 如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

是否是因为你认为你使用的NSArray从零开始?并且第60个对象位于索引59?

答案 1 :(得分:0)

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

int index = [someArraytoCount count] - 1;

someObj *myObj = [otherArray objectAtIndex:index];

另外使用逻辑安全。

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

然后该索引将存在于数组中,您将不会遇到应用程序崩溃

答案 2 :(得分:0)

你是错误的做法:

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”,则检查状态 - 它将如下所示:

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

但是在你的m_dataSource.colors数组中只包含60个对象,这就是为什么它会将数组抛出索引异常。

使用以下代码段替换您的代码:

// 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];

希望这可以帮助您简要介绍数组概念。