为什么一个数组试图在for-loop中超出它的界限?

时间:2015-05-22 16:29:22

标签: objective-c nsarray

我以前从未见过这种情况。我有一个NSArray填充了6个对象。我只使用平均的简单for循环遍历数组抓取值:

for (int i = 0; i <= self.myArray.count; i++) {
        CustomClass *stopTimes = [self.myArray objectAtIndex:i];
        NSLog(@"Hey this number %d: at this time  %lld", i, stopTimes.theTimeRange.start.value);
    }

当此循环运行时,每次都会因为只访问数组之外​​的1个索引而崩溃。在这种情况下有6个项目,它崩溃试图访问第六个。

所以,我转到LLDB并确认数组中确实有6个对象:

(lldb) po self.myArray
<__NSArrayM 0x16bf8620>(
<NeededObject: 0x16bf9f40>,
<NeededObject: 0x16ceO1c0>,
<NeededObject: 0x16ce4268>,
<NeededObject: 0x16cf0b75>,
<NeededObject: 0x16b06d22>,
<NeededObject: 0x16b02240>
)

但是......我的循环中的NSLog只打印出5个对象。 我不知道为什么循环试图访问它的界限之外。有一些黑客可以解决这个问题(例如设置i = 1等)。

3 个答案:

答案 0 :(得分:5)

通过直接将计数作为索引来超越界限。将循环更改为:

for (int i = 0; i < self.myArray.count; i++)

请注意从<=<的更改。

如果数组有三个元素,则索引将为0,1,2,计数将为3.因此,从0循环到计数将导致计数0,1,2,3;其中3超出界限。

答案 1 :(得分:1)

您应该使用for (int i = 0; i < self.myArray.count; i++)

.count()为您提供数组的长度。当索引从0开始时,您最多只能到length of the array - 1

答案 2 :(得分:1)

数组从索引'0'运行到索引'count-1'。你正在运行你的数组来索引'count'。

您应该以这种方式运行循环:

for (int i = 0; i < self.myArray.count; i++) {
    CustomClass *stopTimes = [self.myArray objectAtIndex:i];
    NSLog(@"Hey this number %d: at this time  %lld", i, stopTimes.theTimeRange.start.value);
}

区别是'&lt;'而不是'&lt; ='。