Objective-C循环遍历数组

4
我有类似以下代码的内容:
if (count == 0)
{
    [array1 addObject:@"No Items"];
} 
else
{
    int x;
    for (x = 0;x <= count; x++) 
    {
            [array1 addObject:[itemsArray objectAtIndex:x];
            NSLog(@"%@",array1);
    }
}
itemsArray 中包含数字(0-40)。我期望的结果是:
  • 1
  • 2
  • 3
  • ...
但实际上它却是这样的:
  • 1
  • 1,2
  • 1,2,3
  • 1,2,3,4
  • 1,2,3,4,5
  • ...
为什么会出现这种情况?如果可能的话,我也想请示一个在此情况下使用快速枚举的例子(如果适用)。
提前感谢您的帮助。

可能是因为你在NSLog中输出了整个数组,类似于NSLog(@"%@",[array1 objectAtIndex:x]);或类似的操作。 - Radu
1
看起来你可以使用 addObjectsFromArray: 来替代循环遍历 itemsArray。 - 0xced
2个回答

21
你正在NSLog整个数组,而不是数组1当前的索引。你看到的被记录下来的是你编写的代码 - 要记录你所期望的内容,请将NSLog(@"%@",array1);更改为NSLog(@"%@",[array1 objectAtIndex:x]); 在你的赋值循环之后添加以下内容来确认:
for (NSObject* o in array1)
{
    NSLog(@"%@",o);
}

太棒了!它确实起作用了,我确实不知道如何正确使用 NSLog。我以为快速枚举可以替代 for 循环,它只能用于日志记录吗? - provdr

3

Use NSLog(@"%@", [array1 objectATIndex:x]);

if (count == 0)
{
    [array1 addObject:@"No Items"];
} 
else
{
    int x;
    for (x = 0;x <= count; x++) 
    {
            [array1 addObject:[itemsArray objectAtIndex:x];
            NSLog(@"%@", [array1 objectATIndex:x]);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接