组表视图 - 加载数据

时间:2011-04-17 17:55:48

标签: iphone cocoa-touch ios

寻求有关如何正确加载分组表视图数据的帮助。我正在使用以下代码来加载我认为应为“cellForRowAtIndexPath”准备数组“详细信息”的数据。但是,当我运行程序时,我得到所有组的相同数据,它恰好是我的数据中的最后一行(在NSArray中称为“用户”)。显然我做错了但不确定是什么......请帮忙。

// Customize the number of rows in the table view.

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

NSRange aRange;
aRange.length = 9; aRange.location = 16;
NSString *users = [self.Users objectAtIndex: section];
NSString *subtitle = [NSString stringWithString:[users substringWithRange:aRange]];
details = [[NSArray arrayWithObjects:subtitle, subtitle, subtitle, nil] retain];

return [details count];

}

数据加载例程如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell.
UIImage *cellImage = [UIImage imageNamed:@"world.png"];
cell.imageView.image = cellImage;
cell.textLabel.text = [details objectAtIndex:indexPath.row];
return cell;

}

1 个答案:

答案 0 :(得分:0)

根据您发布的内容,每次表视图向其数据源询问某个部分中的行数时,都会重置details数组。最后一次调用details时最后设置-tableView:numberOfRowsInSection:,即最后一部分。设置后,同一个数组为所有部分提供cell.textLabel.text的数据。所以你得到的数据不正确。

将所有details数组计算并存储在不同的数组中是合适的,比如说detailsArray
然后可以像扫描那样访问数据     [[detailsArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]

您的代码的另一个问题是,每次调用numberOfRowsInSection时,数据都会被泄露,因为重置details而没有释放早期对象。

相关问题