为什么数组会尝试在 for 循环中访问超出其范围的内容?
Why would an array try to access beyond it's bounds in a for-loop?
我以前从未见过这种情况。我有一个 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 等)。
您将计数作为索引,这是越界了。将循环更改为:
for (int i = 0; i < self.myArray.count; i++)
请注意从 <=
到 <
的变化。
如果一个数组有三个元素,则索引为0、1、2,计数为3。因此,从0循环到计数将导致计数为0、1、2、3;其中 3 在边界之外。
你应该使用for (int i = 0; i < self.myArray.count; i++)
.count()
给出数组的长度。由于索引从 0 开始,您最多只能达到 length of the array - 1
.
从索引“0”到索引 'count-1' 的数组 运行s。您正在 运行 将数组编入索引 '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);
}
区别是“<”而不是“<=”。
我以前从未见过这种情况。我有一个 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 等)。
您将计数作为索引,这是越界了。将循环更改为:
for (int i = 0; i < self.myArray.count; i++)
请注意从 <=
到 <
的变化。
如果一个数组有三个元素,则索引为0、1、2,计数为3。因此,从0循环到计数将导致计数为0、1、2、3;其中 3 在边界之外。
你应该使用for (int i = 0; i < self.myArray.count; i++)
.count()
给出数组的长度。由于索引从 0 开始,您最多只能达到 length of the array - 1
.
从索引“0”到索引 'count-1' 的数组 运行s。您正在 运行 将数组编入索引 '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);
}
区别是“<”而不是“<=”。