0

向下滚动表格视图时出现此错误:

2012-04-23 09:32:36.763 RedFox[30540:207] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 12 beyond bounds [0 .. 11]'
*** First throw call stack:
(0x13c3052 0x1554d0a 0x13af674 0x5794 0xb3e0f 0xb4589 0x9fdfd 0xae851 0x59322 0x13c4e72 0x1d6d92d 0x1d77827 0x1cfdfa7 0x1cffea6 0x1cff580 0x13979ce 0x132e670 0x12fa4f6 0x12f9db4 0x12f9ccb 0x12ac879 0x12ac93e 0x1aa9b 0x2158 0x20b5)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
Current language:  auto; currently objective-c

在我的 .h 文件中,我有:

@interface MyTableView : UIViewController  <UITableViewDataSource> {
    int currentRow;
}

@property (strong,nonatomic) UITableView *tableView;
@property (strong,nonatomic) ViewBuilder *screenDefBuild;

在我的 .m 文件中:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [screenDefBuild.elementsToTableView count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
    }

    ScreenListElements *currentScreenElement = [screenDefBuild.elementsToTableView objectAtIndex:currentRow]; //exception points here!
    cell.textLabel.text = currentScreenElement.objectName;

    currentRow++;    
    return cell;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    [tableView setDataSource:self];
    [self.view addSubview:tableView];
}

那有什么问题?

4

2 回答 2

2

currentRow变量是不必要的并且会导致问题!

修理:

换行

 ScreenListElements *currentScreenElement = [screenDefBuild.elementsToTableView objectAtIndex:currentRow]; //exception points here!

 ScreenListElements *currentScreenElement = [screenDefBuild.elementsToTableView objectAtIndex:indexPath.row]; //exception points here!

原因:

currentRow每次cellForARowAtIndexPath:调用时都会递增,这是错误的,因为此方法不仅在显示以下单元格时(向下滚动时)调用,而且在向上滚动时调用(因此currentRow应该递减)。这就是 Apple 放置参数的原因,indexPath以便您可以轻松确定 tableView 正在请求哪个单元格。

于 2012-04-23T07:50:31.813 回答
1

currentRow 对我来说真的没有意义。要返回包含一行源数组 (elementsToTableView) 的单元格,您需要询问当前索引路径中的行。

您的引起错误的行应如下所示:

ScreenListElements *currentScreenElement = [screenDefBuild.elementsToTableView objectAtIndex: indexPath.row];

而且您根本不需要 currentRow 。你为什么以这种方式实施它?

于 2012-04-23T07:50:33.630 回答