【问题标题】:Reload UITableView Data without reloading the view?重新加载 UITableView 数据而不重新加载视图?
【发布时间】:2011-10-11 07:31:12
【问题描述】:

我有一个UITableView,其中包含一堆项目,每次通过refreshRows 方法加载表格时,我都会从Web 应用程序获取这些项目的状态。完成此操作后,我重新加载表。

当我向表中添加项目时,我发现自己收到一条消息“无效更新:部分中的行数无效”。事实证明重新加载表中的数据是必要的,因此我将旧的viewDidAppear 方法更改为新的viewDidAppear 方法(如下所示)。我现在有两个reloadData 调用,它们都刷新了我的视图。

问题:有没有更清洁的方法来做到这一点?添加后我需要重新加载我的数据,但我不希望在获取来自网络的所有状态之前重新加载视图。

- (void)viewDidAppear:(BOOL)animated // new
{
    NSLog(@"viewDidAppear");
    [super viewDidAppear:animated];

    [self.tableView reloadData]; // <------------- Prettier way to do this?
    [self refreshRows];
    [self.tableView reloadData];

}

- (void)viewDidAppear:(BOOL)animated // old
{
    NSLog(@"viewDidAppear");
    [super viewDidAppear:animated];

    [self refreshRows];
    [self.tableView reloadData];

}

- (void)refreshRows {
    // foreach row get status from webapp
}

编辑:

这是请求的代码:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = 
    [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

【问题讨论】:

  • 你能发布你的 numberOfRowsInSection 方法吗?您是否使用 insertRowsAtIndexPaths 将项目添加到表中?您提到的错误通常是在您调用 tableView 插入方法而不更新模型时引起的。
  • 这就是正在发生的事情......但是有一种方法可以在不重新加载视图的情况下重新加载模型?

标签: iphone ios uitableview core-data


【解决方案1】:

如果只有您的数据源知道更改(并且应该注意这一点),您可以尝试这样做:

  1. 注册您的 TableView 以观察通知中心的数据源更新。
  2. 从数据源向 NSNotificationCenter 发布更新已经到来的通知。
  3. 使用 [self.tableView reloadData] 响应 TableView 中的更新;

在数据源中:

- (void) dataSourceChanged
{

    // All instances of TestClass will be notified
    [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"myUniqueDataSourceChanged" 
        object:self];

}

在表视图控制器中:

- (void)viewDidAppear:(BOOL)animated // new
{
    NSLog(@"viewDidAppear");
    [super viewDidAppear:animated];

    [self.tableView reloadData]; // <------------- Prettier way to do this?
    [self refreshRows];
    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(receiveNotification:) 
        name:@"myUniqueDataSourceChanged"
        object:self.dataSource];
}

- (void) receiveNotification:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"myUniqueDataSourceChanged"])
        [self dataSourceHasBeenChanged];
}

- (void) dataSourceHasBeenChanged
{

    [self.tableView reloadData];
    [self refreshRows];
}

这将在每次更新数据源时自动更新您的表格视图

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2023-03-31
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    相关资源
    最近更新 更多