我在我的应用中使用CloudKit,并且在表格视图中遇到显示数据的问题。在viewDidLoad()
中,我从CloudKit数据库中获取数据。
然后在表视图函数中,我对行数进行CKRecord
对象计数。
但count会返回0到表视图,几秒后返回行数。由于此表视图未显示结果。
override func viewDidLoad() {
super.viewDidLoad()
loadNewData()
}
func loadNewData() {
self.loadData = [CKRecord]()
let publicData = CKContainer.default().publicCloudDatabase
let qry = CKQuery(recordType: "Transactions", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
qry.sortDescriptors = [NSSortDescriptor(key: "Transaction_ID", ascending: true)]
publicData.perform(qry, inZoneWith: nil) { (results, error) in
if let rcds = results {
self.loadData = rcds
}
if error != nil {
self.showAlert(msg: (error?.localizedDescription)!)
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return loadData.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath) as! ViewAllTransactionsTVCell
let pn = loadData[indexPath.row].value(forKey: "Party_Name") as! String
let amt = loadData[indexPath.row].value(forKey: "Amount") as! String
let nrt = loadData[indexPath.row].value(forKey: "Narattions") as! String
let dt = loadData[indexPath.row].value(forKey: "Trans_Date") as! String
cell.partyNameLabel.text = pn
cell.dateLabel.text = dt
cell.narationLabel.text = nrt
cell.amountLabel.text = amt
return cell
}
答案 0 :(得分:2)
您不应该等待,而是在调用window.addEventListener("load", globalFunction);
完成处理程序时触发重新加载数据:
perform
注意,我正在将重新加载进程分派到主队列,因为您无法保证在主线程上运行此操作。正如the documentation所说:
您的块必须能够在应用程序的任何线程上运行...
因为UI更新必须在主线程上发生(并且因为您想要同步对publicData.perform(qry, inZoneWith: nil) { (results, error) in
if let rcds = results {
DispatchQueue.main.async {
self.loadData = rcds
self.tableView.reloadData()
}
}
if error != nil {
self.showAlert(msg: (error?.localizedDescription)!)
}
}
的访问权限),所以只需将其发送到主队列,如上所述。