OGeek|极客世界-中国程序员成长平台

标题: iphone - 重新加载 UITableView 数据而不重新加载 View ? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 17:42
标题: iphone - 重新加载 UITableView 数据而不重新加载 View ?

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

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

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

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

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

}

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

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

}

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

编辑:

这是请求的代码:

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



Best Answer-推荐答案


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

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

在数据源中:

- (void) dataSourceChanged
{

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

}

在 TableView Controller 中:

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

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

- (void) receiveNotificationNSNotification *) notification
{
    if ([[notification name] isEqualToString"myUniqueDataSourceChanged"])
        [self dataSourceHasBeenChanged];
}

- (void) dataSourceHasBeenChanged
{

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

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

关于iphone - 重新加载 UITableView 数据而不重新加载 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7722711/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4