我在之前的问题How to use completion handlers correctly中提到过。响应非常好,但我想知道如果函数无效而不是返回值,我将如何执行类似的任务。例如,假设我想运行Parse查询,它收集信息并将其存储在一些局部变量中以填充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()
}
}
}
然后在调用cellForRowAtIndexPath时,我需要使用解析查询中的信息填充表数据。因此,loadDataFromParse函数必须在cellForRowAtIndexPath尝试访问数据之前完成运行。我如何设置完成处理程序以确保发生这种情况?
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
}
编辑:当我在viewDidLoad中调用loadDataFromParse函数时,上面的代码工作正常。当用户拉动刷新tableView时,我再次调用它时发生错误。我还编写了代码作为我的确切代码,因为有些评论表明它可能有用