我有一个视图控制器,可以对运动员进行评估。导航栏中有一个下一个按钮,可以加载下一个运动员。我试图通过以下代码逐步执行我的数组,但每次索引返回为2?我不知道为什么!我错过了什么吗?
-(void)viewDidAppear:(BOOL)animated{
NSUInteger editIndex = [_athleteArray indexOfObject:_currentAthlete];
NSUInteger index = editIndex-1;
Athlete *count = _athleteArray[index];
NSLog(@"Current Athlete:%@ Index: %lu",count,(unsigned long)index);
}
-(void)whenNextButtonIsTapped{
//stuff
NSUInteger editIndex = [_athleteArray indexOfObject:_currentAthlete];
NSUInteger index = editIndex-1;
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);
}
else{
if(index == ((_athleteArray.count)-1)){
_evalSelected = [self getMostRecentEval];
[self updateInformation];
index=0;
NSLog(@"Index after being equal to array count: %lu",(unsigned long)index);
}
}
self.title = [NSString stringWithFormat:@"%@'s Evaluation",_evalSelected.whosEval.full];
}
}
-(Eval *)getMostRecentEval{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"whosEval == %@", _currentAthlete];
[request setPredicate:predicate];
NSEntityDescription *eval = [NSEntityDescription entityForName:@"Eval" inManagedObjectContext:_managedObjectContext];
[request setEntity:eval];
NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"date_recorded"
ascending:NO
selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil){
//handle error
}
NSMutableArray *lastEvalArray = mutableFetchResults;
return lastEvalArray.firstObject;
}
奇怪的行为是a)当出现视图时,不管是谁被点击,索引是2.和b)它没有进入下一个运动员的评估,它是同一个人,它是最后一个人索引。
答案 0 :(得分:1)
您正在将editIndex定义为currentAthlete的索引。然后从中减去1得到索引,然后将1加回(使用索引++),最后将currentAthlete设置为_athleteArray [index],这将是您开始使用的同一个运动员。您应该能够通过不使用索引来修复它,只需使用editIndex。