数据从数据库中检索后重新加载UiTableView - Swift

问题描述 投票:0回答:2

如何在从数据库加载数据后重新加载UiTableView。我有一个数据源类,其中包含加载所有数据的函数,并在数据加载到数组后存储数据。

当我使用Tableview访问数据时虽然它没有显示任何内容,因为在数据库返回其数据之前加载了tableview。加载数据的唯一方法是让我有一个手动重新加载tableview的按钮。

一旦从数据库填充数据源对象中的数组,如何使tableview自动重新加载?

ios database uitableview asynchronous
2个回答
3
投票

作为一名新的程序员,我花了一段时间来学习这一点甚至是可能的,但我刚刚意识到完成块是要走的路。只有在函数从数据库中取出后,它才会执行一些指定的代码。在这种情况下,我可以在从数据库中检索数据后更新tableview。这是一个例子。

功能定义:

func getDataFromDatabase(someInput: Any, completion: @escaping(String?) -> Void) {
    let retrievedData: String = databaseCallFunction()        
    // 'Get data from database' code goes here
    // In this example, the data received will be of type 'String?'
    // Once you've got your data from the database, which in this case is a string
    // Call your completion block as follows
    completion(retrievedData)
}

如何调用该函数:

getDataFromDatabase(someInput: "Example", completion: { (data) in 
    // Do something with the 'data' which in this example is a string from the database
    // Then the tableview can be updated
    let tableView.title = data
    tableView.reloadTableView
})

完成块中的代码将在数据库调用完成后发生。


2
投票

为什么不在填充数据后调用tableView.reloadData()?它将重新填充整个表格(从技术上讲,它只会重新创建任何可见的单元格)。

关键是你的tableView:cellForRowAt:方法应该能够访问你的数据,以便根据这些数据适当填写每个表格单元格。无论何时数据发生变化,只需再次调用tableView的reloadData()。它的有效之处在于只创建了可见的单元格,并且只要它们即将变得可见,其余部分就会被创建。

此外,tableView:numberOfRowsInSection:同样应该查看您的数据以判断应存在多少行。在每次调用reloadData()期间也会再次调用它。

您的数据应始终准备好由tableView委托方法查询,即使它还没有包含任何内容。当没有数据时,tableView:numberOfRowsInSection:将决定应该有0行。

© www.soinside.com 2019 - 2024. All rights reserved.