当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - How can I add CKRecords to an array before using that array to fill cells in a UITableView in Swift?

问题描述:

I have been trying to use a fetchRecords function to fill an array of CKRecords to fill a UITableView of cells. When I run the app, the UITableView calls the numberOfRowsInSection function before the fetchRecords function.

func fetchRecords(){

let predicate = NSPredicate(value: true)

let query = CKQuery(recordType: "Counter", predicate: predicate)

let queryOperation = CKQueryOperation(query: query)

queryOperation.recordFetchedBlock = { (record : CKRecord!) in

self.objects.append(record)

println("recordFetchedBlock: \(record)")

}

cloudKitHelper.privateDB.addOperation(queryOperation)

/*

cloudKitHelper.privateDB.performQuery(query, inZoneWithID: nil, completionHandler: {(results, error) ->Void in

if error != nil{

println(error)

}

else {

println(results)

for result in results{

self.objects.append(result as! CKRecord)

println(self.objects[0].valueForKey("Title"))

println(self.objects[0].valueForKey("Count"))

}

}

})*/

}

I have tried using both addOperation and performQuery to obtain the records. Both seem to work properly, they just obtain the records after the UITableView has already run the numberOfRowsInSection method, which returns objects.count

override func viewDidLoad() {

super.viewDidLoad()

fetchRecords()

As you can see, fetchRecords() is the first thing called in viewDidLoad() after the super call.

I'm trying to figure out how to load the objects array with the CKRecords before the UITableView loads

网友答案:

You need to update UI elements on the main dispatch thread. The recordFetchedBlock is going to be called multiple times - presumably, each time, as records become available, you'll want to update your table view. Try this:

queryOperation.recordFetchedBlock = { (record : CKRecord!) in
  println("recordFetchedBlock: \(record)")
  dispatch_async (dispatch_get_main_queue()) {
    self.objects.append(record)
    self.tableView.reloadData()
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: