Swift后重新加载表
问题描述:
我想重新加载我的tableView后,从Parse中删除一个对象。 我尝试self.tableView.reloadData()
在我的完成处理程序,甚至得到一个print
语句告诉我什么时候完成但我的表不重新加载。Swift后重新加载表
@IBAction func trashButtonPressed(sender: UIButton) {
print("Button pressed")
let alertController = UIAlertController(title: "Alert", message: "Do you want to delete all recent games?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
}
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
for game in self.games[3] {
game.deleteInBackgroundWithBlock({ (success, error) -> Void in
if error == nil {
self.tableView.reloadData()
print("Did delete game? \(success)")
}
})
}
}
alertController.addAction(cancelAction)
alertController.addAction(OKAction)
presentViewController(alertController, animated: true, completion: {() -> Void in
print("Alert was shown")
})
}
我在做什么错?我应该在哪里放self.tableView.reloadData()
?
编辑
我试图让主队列,像这样:
game.deleteInBackgroundWithBlock({ (success, error) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.tableView.reloadData()
})
print("Did delete game? \(success)")
} else {
print("Error: \(error)")
}
})
表仍然没有重新加载,当我按下OK
答
您可能会看到此行为如果-deleteInBackgroundWithBlock:
不会在主线程中调用您的块。假设你想在背景上执行你的块也是合理的。我在Parse文档中找到它,但它没有说明它是否在主线程上返回。
如果这确实是问题,你能解决这个问题是这样的:
game.deleteInBackgroundWithBlock({ (success, error) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue(), ^{
self.tableView.reloadData()
})
}
})
答
如果您正在使用PFQueryTableViewController你可以尝试致电
loadObjects()
,而不是self.tableView.reloadData()
答
我在deleteInBackgroundWithBlock之后使用了defer {...},所以它实际上适用于我的情况。
object.deleteInBackgroundWithBlock(nil)
defer {
array = [] // remove all object in the array that you query before
queryParse() // query new object from Parse (without deleted object)
tableView.reloadData() // reload tableView
}
至少在主线程上调用'reloadData()'。 – vadian
我对Parse没有经验,但根据https://parse.com/questions/what-thread-does-findobjectsinbackgroundwithblock-complete-on,所有完成块都在主线程上执行。另一方面,这里http://*.com/questions/29879884/ios-tableview-begin-updates-never-plays-animation它声称你需要派遣到主线程。 –