我的 ViewController 想要显示一些基于 CloudKit 查询的数据。
我的 CloudKit 代码都在一个单独的类中。该类有一个名为 loadExpenses() 的函数,它从 CK 获取一些 Expenses 实体。
我希望能够从 VC 调用 loadExpenses(),因此我需要该函数提供的完成块来从 VC 更新 UI。
这就是 loadExpenses() 的样子:
func loadExpenses() {
let pred = NSPredicate(value: true)
let sort = NSSortDescriptor(key: "creationDate", ascending: true)
let query = CKQuery(recordType: "Expense", predicate: pred)
query.sortDescriptors = [sort]
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["person", "action", "amount", "timestamp"]
operation.resultsLimit = 50
var newExpenses = [Expense]()
operation.recordFetchedBlock = { (record) in
let recordID = record.recordID
let person = record["person"] as! String
let action = record["action"] as! String
let amount = record["amount"] as! Double
let timestamp = record["timestamp"] as! NSDate
let expense = Expense(person: person, action: action, amount: amount, timestamp: timestamp)
newExpenses.append(expense)
}
// This is the part that needs to be changed
operation.queryCompletionBlock = { [unowned self] (cursor, error) in
dispatch_async(dispatch_get_main_queue()) {
if error == nil {
self.objects = newExpenses
self.tableView.reloadData()
self.refreshRealmDataFromCK()
} else {
let ac = UIAlertController(title: "Fetch failed", message: "There was a problem fetching the list of expenses; please try again: \(error!.localizedDescription)", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(ac, animated: true, completion: nil)
}
}
}
CKContainer.defaultContainer().privateCloudDatabase.addOperation(operation)
}
显然最后一部分不会执行,考虑到所有这些 self.property 属于 VC(我保留它们只是为了展示我需要在 VC 中做什么)。
正如我所说,我希望能够从 VC 调用此函数并获取/使用完成块来更新这些属性。我怎么做?