向下滚动时GridView总是崩溃

时间:2012-10-17 13:39:10

标签: objective-c ios uitableview core-data gridview

我想用数据填充gridView。我正在使用从Web服务返回的数据执行此操作。为了填充我有一个属性loopIndex,它计算数组的哪个对象应该是下一个单元格。你可以在这里看到CellForRowAtIndexPath方法。

- (NRGridViewCell*)gridView:(NRGridView *)gridView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyCellIdentifier = @"MyCellIdentifier";

    NRGridViewCell* cell = [gridView dequeueReusableCellWithIdentifier:MyCellIdentifier];

    if(cell == nil){
        cell = [[NRGridViewCell alloc] initWithReuseIdentifier:MyCellIdentifier];

        [[cell textLabel] setFont:[UIFont boldSystemFontOfSize:11.]];
        [[cell detailedTextLabel] setFont:[UIFont systemFontOfSize:11.]];

    }
    NSLog(@"loopIndex: %d",_loopIndex);
    _players = [self getTeam];

       NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[[_players objectAtIndex:_loopIndex]valueForKey:@"image"]]];
       UIImage *image = [[UIImage alloc]initWithData:imgData];
       cell.imageView.image = image;
        cell.textLabel.text = [[_players objectAtIndex:_loopIndex]valueForKey:@"name"];
        cell.detailedTextLabel.text = [[_players objectAtIndex:_loopIndex]valueForKey:@"position"];
    if(_loopIndex < [[self getTeam]count]){
    _loopIndex++;
    }else {
        _loopIndex = _loopIndex;
    }
    return cell;
}

在这里您可以看到错误。它始终在NSData线上崩溃。

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[_PFArray objectAtIndex:]: index (30) beyond bounds (30)'

我认为我的loopIndex存在问题。因为当我只使用静态值时。假设1O喜欢这个

 cell.textLabel.text = [[_players objectAtIndex:_loopIndex]valueForKey:@"name"]; 

它不会崩溃。有谁知道如何解决它?

亲切的问候

2 个答案:

答案 0 :(得分:0)

尝试

    _loopIndex++;
    if(_loopIndex >= [[self getTeam]count]){
        _loopIndex = [[self getTeam]count]-1;
    }

要做得好,你应该做如下:

cell = // new default cell;

// calculate _loopindex for next attempt
if (_loopindex < [[self getTeam]count])
{
    //do your job
}

return cell;

如果在section和table中设置了正确的行数,则应该根据需要调用方法gridView cellForItemAtIndexPath的确切次数。不多也不少。这样可以防止您返回零或错误计算_loopindex计数器。

答案 1 :(得分:0)

您错误地计算_loopindex这就是您收到错误的原因,但更重要的是您应该依赖indexPath变量而不是您正在计算的索引来显示此协议方法中的数据。

相关问题