当用户长按一个单元格并确认更改时,我编写了一些代码来从后端删除帖子和本地数据存储。但是tableview不会更新。我已经打破了我的代码并执行了tableView操作代码,为什么我的行没有从视图中删除?
let alertView = UIAlertController(title: "Really?", message: "Are you sure you want to delete this post? Once you do it will be gone forever.", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Delete Post", style: UIAlertActionStyle.Default, handler: { (alertView:UIAlertAction!) -> Void in
let p = post.getRawPost()
p.deleteInBackgroundWithBlock({ (deleted:Bool, error:NSError?) -> Void in
// Remove from the local datastore too
p.fetchFromLocalDatastore()
p.deleteInBackgroundWithBlock({ (deleted:Bool, error:NSError?) -> Void in
// Update the table view
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.tableView.endUpdates()
})
})
}))
据我了解,beginUpdates
和endUpdates
用于更新tableView的特定部分,而无需在源上执行完整的reloadData
调用。我在这里错过了什么吗?
UPDATE 我将tableView更新代码移动到主线程,每当调用endUpdates
时都会发生崩溃。我的新代码如下所示,并在主线程上调用:
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row, inSection: indexPath.section)], withRowAnimation: UITableViewRowAnimation.Automatic)
self.tableView.endUpdates()
答案 0 :(得分:1)
将代码段包含在 MAIN THREAD 中:
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.tableView.endUpdates()
p.deleteInBackgroundWithBlock({ (deleted:Bool, error:NSError?) -> Void in
// Remove from the local datastore too
p.fetchFromLocalDatastore()
// Delete the desired item from array
...
// Remove cell that the item belong to animated in main thread
dispatch_async(dispatch_get_main_queue(), {
// Update the table view
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
})
})