[英]tableView(_: cellForRowAtIndexPath) is not called and TableView doesn't show any data
I put a Table View Controller and embed in to a Navigation Controller on IB. 我放置了一个表视图控制器,并嵌入到IB上的导航控制器中。 After that I create a WalletsTableViewController class with the following code: 之后,我使用以下代码创建WalletsTableViewController类:
class WalletsTableViewController: UITableViewController {
private var wallets = [Wallet]()
override func viewDidLoad() {
super.viewDidLoad()
fetchWallets()
}
private func fetchWallets(){
let managedObjectContext = AppDelegate.managedContext
let fetchRequest: NSFetchRequest<Wallet> = Wallet.fetchRequest()
do {
wallets = try managedObjectContext.fetch(fetchRequest)
} catch {
print(error.localizedDescription)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection: Int) -> Int {
return wallets.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WalletCell", for: indexPath)
let wallet = wallets[indexPath.row]
cell.textLabel?.text = wallet.name
return cell
}
}
I implement a persistent application that's why I have the fetchWallets() method and it works well. 我实现了一个持久性应用程序,这就是为什么我有fetchWallets()方法并且它运行良好的原因。 I can print the data to the console but the tableView doesn't want to show my elements. 我可以将数据打印到控制台,但tableView不想显示我的元素。 Moreover the implemented tableView() methods are not called. 此外,不调用已实现的tableView()方法。 How can I fix this problem? 我该如何解决这个问题?
EDIT: tableView.reloadData() did not help 编辑: tableView.reloadData()没有帮助
As suggested in the comments above try the following: 如以上注释中所建议,请尝试以下操作:
private func fetchWallets(){
let managedObjectContext = AppDelegate.managedContext
let fetchRequest: NSFetchRequest<Wallet> = Wallet.fetchRequest()
do {
wallets = try managedObjectContext.fetch(fetchRequest)
self.tableView.reloadData()
} catch {
print(error.localizedDescription)
}
}
you need to reload table view in main thread use the below code 您需要使用以下代码在主线程中重新加载表视图
private func fetchWallets(){
let managedObjectContext = AppDelegate.managedContext
let fetchRequest: NSFetchRequest<Wallet> = Wallet.fetchRequest()
do {
wallets = try managedObjectContext.fetch(fetchRequest)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error.localizedDescription)
}
}
Hope this will help you 希望这个能对您有所帮助
My bad... I did not delete the autoimplemented functions. 糟糕...我没有删除自动实现的功能。 This has solved my problem. 这解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.