【问题标题】:Can't find object's location in array?在数组中找不到对象的位置?
【发布时间】:2013-09-11 00:16:47
【问题描述】:

我有一个可以评估运动员的视图控制器。导航栏中有一个下一步按钮,可以加载下一个运动员。我正在尝试使用以下代码单步执行我的数组,但每次索引都返回为 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)它不会进入下一个运动员的评估,它是同一个人,它是最后一个人索引。

【问题讨论】:

    标签: ios objective-c cocoa-touch cocoa core-data


    【解决方案1】:

    您将 editIndex 定义为 currentAthlete 的索引。然后从中减去 1 以获得索引,然后将 1 加回(使用 index++),最后将 currentAthlete 设置为 _athleteArray[index],这将与您开始使用的运动员相同。您应该可以完全不使用 index 来修复它,只需使用 editIndex。

    【讨论】:

    • 我犯过的最愚蠢的错误。不知道为什么一开始就在那里。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2017-04-24
    • 2014-05-11
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多