I asked in an earlier question How to use completion handlers correctly. The response was excellent, but i was wondering how i would perform a similar task if the function was void rather than returning a value. For example, say i want to run a Parse query, that gathers information and stores it in some local variables to populate a UITableView
func loadParseData () {
commentsArray.removeAll(keepCapacity: false)
let query = PFQuery(className: "Comments")
query.whereKey("answerId", equalTo: answerId)
var tempArray : [comment] = []
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
let newComment = comment(comment: object["commentText"] as! String, username: object["Username"] as! String)
tempArray.append(newComment)
}
self.commentsArray = tempArray
self.tableView.reloadData()
}
}
}
Then upon calling the cellForRowAtIndexPath, i need to populate the table data with information from the parse query. Because of this, the loadDataFromParse function must finish running before the cellForRowAtIndexPath tries to access the data. How would i set up a completion handler to ensure this happens?
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! commentCellTableViewCell
cell.commentTextField.text = commentsArray[indexPath.row].comment
cell.usernameTextField.text = commentsArray[indexPath.row].username
return cell
}
EDIT: The above code works perfectly when i call the loadDataFromParse function in viewDidLoad. It is when i call it again when the user pulls to refresh the tableView that the error occurs. I have also edited the code to be my exact code, due to the fact that some comments were indicating it might be helpful