2013-07-08 178 views
1

我有一个while循环应该循环遍历一个条件,但不能多次遍历整个过程。Objective C虽然循环不循环

这是我的相关代码:

NSInteger i = 0; 
    while(i <= building.departments.count) 
    { 
     NSLog(@"Number of building departments: %lu", (unsigned long)building.departments.count); 
     NSLog(@"i : %ld", (long)i); 

     UILabel *dtitleLB = [[UILabel alloc] initWithFrame:CGRectMake(5, y, 310, 20)]; 
     dtitleLB.text = ((DBDepartment*)[building.departments objectAtIndex:i]).Name; 
     dtitleLB.textAlignment = UITextAlignmentLeft; 
     dtitleLB.backgroundColor = [UIColor clearColor]; 
     dtitleLB.textColor = [UIColor lightGrayColor]; 
     dtitleLB.font = [UIFont fontWithName:@"Helvetica" size:(16.0)]; 
     [scrollView addSubview:dtitleLB]; 
     y += 30; 

     UIButton* dphoneNB = [UIButton buttonWithType:UIButtonTypeCustom]; 
     [dphoneNB setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; 
     [dphoneNB setTitleColor:[UIColor colorWithRed:0.3 green:0.3 blue:0.9 alpha:1.0] forState:UIControlStateNormal]; 
     [dphoneNB addTarget:self action:@selector(numberPress:) forControlEvents:UIControlEventTouchUpInside]; 
     [dphoneNB setTitle:((DBDepartment*)[building.departments objectAtIndex:i]).Phone forState:UIControlStateNormal]; i++; 
     dphoneNB.frame = CGRectMake(5, y, 315, 25); 
     [scrollView addSubview:dphoneNB]; 
     y += 30; 

     UIButton* dwebsiteNB = [UIButton buttonWithType:UIButtonTypeCustom]; 
     [dwebsiteNB setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; 
     [dwebsiteNB setTitleColor:[UIColor colorWithRed:0.3 green:0.3 blue:0.9 alpha:1.0] forState:UIControlStateNormal]; 
     [dwebsiteNB addTarget:self action:@selector(linkPress:) forControlEvents:UIControlEventTouchUpInside]; 
     [dwebsiteNB setTitle:((DBDepartment*)[self->building.departments objectAtIndex:i - 1]).Website forState:UIControlStateNormal]; i++; 
     dwebsiteNB.frame = CGRectMake(5, y, 315, 25); 
     [scrollView addSubview:dwebsiteNB]; 
     y += 30; 

     i++; 
    } 

用于第一的NSLog = 1或更大的取决于用户的选择(从未0)输出。 第二个NSLog = 0的输出永远不会变大。

如果你可以检查我的代码,看看是否有任何明显的错误,那将不胜感激。

谢谢!

+1

“building.departments.count”是否等于0或1?你似乎也在几个地方增加了“我”。 –

+0

aso在顶部的2个NSLog的输出会很好 – John

+0

你有多少个部门? –

回答

1

不循环(或循环不规律)的原因是因为您在多个点中增加了i。看下面的几行(打破了看起来更容易)。

... 
     [dphoneNB setTitle:((DBDepartment*)[building.departments 
     objectAtIndex:i]).Phone forState:UIControlStateNormal]; i++; 
... 
     [dwebsiteNB setTitle:((DBDepartment*)[self->building.departments 
     objectAtIndex:i - 1]).Website forState:UIControlStateNormal]; i++; 
... 
     i++; 

作为替代while环这样的,一个for循环就足够了。

+0

非常感谢你在那里发现我的错误,你完全发现了错误! – VonKoob

+0

有时候,第二组眼睛使所有的区别:) –

+0

@VonKoob原始代码也非常低效。为什么一遍又一遍地提取'Department'对象?在循环的顶部获取一次,并将其存储在一个变量中。更好的是,使用'for(DBDepartment * dept in building.departments)'而不是'while'循环。 – rmaddy