只有第一个For循环调用

mic*_*ela 1 iphone for-loop subview

我有两个for循环,它们为视图添加了子视图.第一个添加所有子视图,但第二个for循环甚至没有执行!这是怎么回事?

- (void)createBoxes
{
    for (int i; i<5; i++) {
        GameBox *box = [[GameBox alloc] initWithFrame:CGRectMake((i * 64) + 7, 50, 50, 50)];
        [self.view addSubview:box];
    }
    for (int e; e<5; e++) {
        GameBox *box1 = [[GameBox alloc] initWithFrame:CGRectMake((e * 64) + 7, 107, 50, 50)];
        [self.view addSubview:box1];
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 8

正确的方法是初始化变量:

int i = 0;
int e = 0;
Run Code Online (Sandbox Code Playgroud)

否则你永远不会知道你会得到哪个价值.

  • +1.始终需要初始化局部变量.如果你在调试器中检查它,e可能是像3728632873,在这种情况下,它肯定不小于5,你跳过你的循环! (2认同)