简体   繁体   中英

reload tableView AFTER Parse query (serial queue?)

I have a tableView that contains elements of an array. This array is populated by a PFQuery. After the query, the array is sorted by multiple criteria. I want all of this to happen in viewDidLoad BEFORE they show up in the tableView. However, the only way I can get it to populate the tableView is if it happens with in the findObjectsInBackground closure. If it happens after that then the query hasn't completed and therefore the array is empty. I have tried looking at various materials on dispatch queues and it seems to be I need these tasks to be executed serially but I cannot figure out how to do it. Here is the relevant code.

override func viewDidLoad() {
    super.viewDidLoad()

    var getBuddiesQuery = PFQuery(className: "followers")
    getBuddiesQuery.whereKey("userHasBuddy", equalTo: "yes")
    getBuddiesQuery.findObjectsInBackgroundWithBlock {
        (objects, error) -> Void in
        if error == nil {

            self.buddies.removeAll(keepCapacity: true)

            for object in objects! {

                self.buddies.append(object["buddy"] as! String)

                //MULTIPLE SORTS OF ARRAY

                self.tableView.reloadData()

                //IF RELOAD IS HERE THEN IT LOOKS VERY CHOPPY BECAUSE OF SORTS BUT SORTS CAN ONLY HAPPEN HERE FOR SAME REASON - BECAUSE OTHERWISE THE ARRAY HAS NOT BEEN POPULATED
            }
        }
    }
}

Instead of reloading the table for each element you are appending, go through all the elements, append them all to your buddies array, and then reloadData . So your code would look like:

getBuddiesQuery.findObjectsInBackgroundWithBlock {
    (objects, error) -> Void in
    if error == nil {

        self.buddies.removeAll(keepCapacity: true)

        for object in objects! {
            self.buddies.append(object["buddy"] as! String)
        }
        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