【问题标题】:Error with using local variable to access array index使用局部变量访问数组索引时出错
【发布时间】:2015-10-16 08:44:27
【问题描述】:

由于某种原因,每次我尝试通过在 forloop 的索引中指定变量 int 来访问数组中的特定索引时,都会发生这种情况。当我这样做时,我得到一个线程 1 错误,但如果我使用一个尚未在 forloop 本身中声明的变量,它似乎工作正常。 代码:

for(int i =0 ; i<= [array count]; i++) {
    NSNumber *convert = [array objectAtIndex:i]; //results in error
    NSLog(@"%i", [convert intValue]);
   }

【问题讨论】:

  • @Alexander Iam 为 xCode 使用 LLVM 编译器。
  • 在第一个示例中,错误在 i

标签: objective-c arrays for-loop local-variables


【解决方案1】:

问题是您试图访问超出其容量的数组。数组以0 索引开始并上升到array.count - 1。也就是说,请尝试以下代码,您应该会很好:

for (int i = 0 ; i <= array.count - 1 ; i++) {
    NSNumber *convert = [array objectAtIndex:i];
    NSLog(@"%i", [convert intValue]);
}

另一种变化可能是:

for (int i = 0 ; i < array.count ; i++) {
    NSNumber *convert = [array objectAtIndex:i];
    NSLog(@"%i", [convert intValue]);
}

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    相关资源
    最近更新 更多