我在我的viewController中有这段代码。问题是,当调用两个函数来加载CKRecord对象中的所有数据时。下一行代码执行并打印0作为记录计数。我希望Swift等待这两个函数完成并打印它们的计数。需要帮助来解决这个问题。函数在下一行代码之前完成执行。
override func viewDidLoad() {
super.viewDidLoad()
view1.layer.borderWidth = 1
view1.layer.cornerRadius = 10
tableView.layer.borderWidth = 1
tableView.layer.cornerRadius = 10
loadNewData() // function that loads all partyAccounts
fetchPartyAccounts() // function to load all transactions
print(loadTransactionData.count)
print(partyAccountsData.count)
}
func loadNewData() {
let qry = CKQuery(recordType: "PartyAccounts", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
qry.sortDescriptors = [NSSortDescriptor(key: "Party_ID", ascending: true)]
publicDB.perform(qry, inZoneWith: nil) { (results, error) in
DispatchQueue.main.async {
if let rcds = results {
self.partyAccountsData = rcds
}
}
if error != nil {
self.showAlert(msg: (error?.localizedDescription)!)
}
}
self.tableView.reloadData()
}
func fetchPartyAccounts() {
let qry = CKQuery(recordType: "Transactions", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
qry.sortDescriptors = [NSSortDescriptor(key: "Party", ascending: true)]
publicDB.perform(qry, inZoneWith: nil) { (results, error) in
DispatchQueue.main.async {
if let rcds = results {
self.loadTransactionData = rcds
}
if error != nil {
self.showAlert(msg: (error?.localizedDescription)!)
}
}
}
self.tableView.reloadData()
}
*不要问,告诉*。了解如何理解异步方法的工作原理。将打印行分别放在完成块的末尾。并把行重新加载表视图**也**完成块(在调度块内)。 – vadian