Reputation: 4079
I have written some code to delete a post from the back end and local data storage when a user long presses a cell and confirms the change. However the tableview does not update. I have breakpointed my code and the tableView manipulation code is executed, why is my row not being removed from the view?
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()
})
})
}))
As I understand it, beginUpdates
and endUpdates
is used to update specific sections of a tableView without needing to perform a full reloadData
call on the source. Am I missing something here?
UPDATE I moved the tableView update code to the main thread, this produced a crash whenever endUpdates
is called. My new code looks as below, and is called on the main thread:
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row, inSection: indexPath.section)], withRowAnimation: UITableViewRowAnimation.Automatic)
self.tableView.endUpdates()
Upvotes: 1
Views: 834
Reputation: 35131
Wrap the code snippet below in MAIN THREAD instead:
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)
})
})
Upvotes: 1