2

我有一个 tableView 需要在从另一个视图插入信息后更新。如果我执行

[self.tableView reloadData];

下一次我在另一个视图中插入更多信息并尝试重新加载表时,所有当前可见的行都会重复。

换句话说,当我启动应用程序时,我有:

tableView:
    Row 1
    Row 2

然后我提交了一些信息,这些信息也会显示在表格中,突然间我有了:

tableView
    Row 1
    Row 2
    Row 3 <- info I just added
    Row 1
    Row 2

我的 numberOfRowsInSection 实现如下所示:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [ItemsController sharedItemsController].count;
}

我的 cellForRowAtIndexPath 实现如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ItemsController* controller = [ItemsController sharedItemsController];
    NSMutableArray* recentItems = controller.listOfRecentItems;

    CustomCell *cell = nil;
    NSUInteger row = [indexPath row];

    if( row < recentItems.count )
    {
        Items*  item = [recentItems objectAtIndex:row];
        if( recentCellData == nil )
            recentCellData = [[NSMutableDictionary alloc] initWithCapacity:[indexPath length]];

        if( [recentCellData count] > 0 )
            cell = [recentCellData objectForKey:[NSString stringWithFormat:@"%d", row]];
        if (cell == nil) {
            UIViewController * view1 = [[UIViewController alloc] initWithNibName:@"CustomCell" bundle:nil];

            cell = (CustomCell*)[view1 view];

            [recentCellData setObject:cell forKey:[NSString stringWithFormat:@"%d",row]];
        }

       // do some other stuff here
    }
    // Set up the cell
    return cell;
}

更新表并避免重复当前可见行的最佳方法是什么。提前感谢所有帮助!

4

3 回答 3

3

错误不在于您如何重新加载表,而在于您如何向其提供数据。在数据源方法和添加新行的方法中设置断点以查看哪里出错了。

于 2009-03-26T15:18:37.867 回答
2

tableView:numberOfRowsinSection:如果返回,您最终只会得到五个项目5。这就是您问题的简单答案,但我在这里看到了其他问题。我想知道你为什么要进行这个测试:row < recentItems.count。那个数组和 一样[ItemsController sharedItemsController].count吗?您确实需要为这两种方法使用相同的数组。

(另外,这不是语法错误,但您不应该将属性语法用于未声明为属性的事物。您应该[recentItems count]改为编写。)

我也对您用于设置单元格的代码感到困惑。细胞是可重复使用的。也就是说,您创建一个单元格,然后在每次执行tableView:cellForRowAtIndexPath:. 您的代码为列表中的每个项目创建一个单元格。这是非常低内存效率的,并且如果您像这样在内存中保留大量单元格,则可能会由于 iPhone 上的内存不足而使您的程序崩溃。

推荐的方法是调用dequeueReusableCellWithIdentifier:. 如果返回,那么您使用初始化程序nil设置一个单元格。initWithFrame:reuseIdentifier:表格视图非常智能,只会在需要时要求您重绘单元格。

你的recentCellData字典在我看来也很不稳定。如果您在带有 key 的项目之后插入一个项目@"2"怎么办?所有带有 key @"3"onward 的项目都需要向右移动一个元素才能按您期望的方式工作。这是大量的簿记,对我来说似乎相当不必要。如果你真的需要这样的东西——而且要清楚,我认为你不需要——你为什么不使用NSMutableArray更容易使用的 an 呢?

于 2009-03-26T16:22:57.163 回答
1

我在上面添加了更多信息。

于 2009-03-26T15:52:09.937 回答