我在我的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