【发布时间】:2013-09-11 01:02:38
【问题描述】:
下面的代码应该执行此操作:无论当前运动员在哪里,当您点击下一步按钮时,都会执行下面的代码。它应该将当前运动员更改为数组中的下一个运动员,然后当它到达最后一个人时,它需要循环回 0(第一个对象)。它确实做到了这一点。当我到达数组的末尾时,它会再次转到第一个人,这是正确的,但从那时起将跳过数组中的最后一个对象。知道为什么吗?
-(void)nextAthlete{
NSUInteger index = [_athleteArray indexOfObject:_currentAthlete];
Athlete *count = _athleteArray[index];
NSLog(@"Current Athlete:%@ Index: %lu",count,(unsigned long)index);
if(index < ((_athleteArray.count)-1)){
index++;
_currentAthlete = _athleteArray[index];
_evalSelected = [self getMostRecentEval];
[self updateInformation];
NSLog(@"Index after being smaller than the array count: %lu",(unsigned long)index);
}
if(index == ((_athleteArray.count)-1)){
_currentAthlete = _athleteArray[index];
_evalSelected = [self getMostRecentEval];
[self updateInformation];
index=0;
_currentAthlete = _athleteArray[index];
NSLog(@"Index after being equal to array count: %lu",(unsigned long)index);
}
if(index > ((_athleteArray.count)-1)){
index=0;
_currentAthlete = _athleteArray[index];
}
self.title = [NSString stringWithFormat:@"%@'s Evaluation",_evalSelected.whosEval.full];
}
【问题讨论】:
-
当您设置
index=0时,您需要在执行其他任何操作之前执行此操作。目前index == _athleteArray.count时,在更新索引之前访问数组,导致越界访问。 -
@Mac:我不想要索引为零。它需要从当前运动员所在的位置开始。例如如果我从 5 位中的第 3 位运动员开始,它需要转到 4,然后是 5,然后是 0。
-
index是在循环内部还是外部声明? -
@CarlVeazey:index 在循环之外
-
@JosueEspinosa 嗯...在声明
index的方法中没有循环,因此您的声明与您的代码相矛盾 - 但我想我明白发生了什么。你在做for (int i = 0; i < [_athleteArray count]; i++) { [self nextAthlete]; }之类的事情吗?
标签: ios objective-c cocoa-touch cocoa