简体   繁体   中英

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()
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM