简体   繁体   中英

Error when Removing Row from TableView (Swift)

I want to delete a row from a table view, but it isn't working :/

This next code block is triggered from a custom button (not from an internal Apple-Table-Edit).

self.tableView.beginUpdates()
self.sections[indexPath.section].items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
self.tableView.endUpdates()

This is how a section looks like:

class Section: Comparable {
    var state: TrackingObject.stateEnum
    var items: [TrackingObject]
    var expanded: Bool

    init(state : TrackingObject.stateEnum, items : [TrackingObject], expanded : Bool){
        self.state = state
        self.items = items
        self.expanded = expanded
    }

    static func group(trackingObjects: [TrackingObject]) -> [Section] {
        let groups = Dictionary(grouping: Model.trackingObjects) { (trackingObject: TrackingObject) -> TrackingObject.stateEnum in
            return trackingObject.currentState
        }
        return groups.map { (state: TrackingObject.stateEnum, trackingObjects: [TrackingObject]) in
            return Section(state: state, items: trackingObjects, expanded: state == .active_due ? true : false)
        }.sorted()
    }
}

Expected: That the row of the given indexPath is removed with an animation as well as removed in the 'data source' (called: self.sections)

Actual Output: Error-Message:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 2 into section 0, but there are only 0 rows in section 0 after the update'

(I was removing the second row in the section 0)

self.sections[indexPath.section].items.remove(at: indexPath.row)
    self.tableView.beginUpdates()
    DispatchQueue.main.async {
        tableView.deleteRows(at: [indexPath], with: .automatic)
        self.tableView.endUpdates()
    }

Try removing item from your data source before beginUpdates(). You can also just remove item from the data source and reload the table view as you are setting the animation option as automatic, so tableview will perform the preferable animation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM