EditingStyle - 删除数组中的单元格和项目

时间:2015-09-21 23:32:28

标签: arrays swift uitableview editing

我创建了一个数组

var subjectsData = [ Subject(name: "Investments", semester: 1), Subject(name: "Statistics", semester: 1), Subject(name: "Studium Universale", semester: 2) ]

和tableView

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("SubjectCell", forIndexPath: indexPath) as! SubjectCell

    let subject = subjects[indexPath.row] as Subject
    let Semester = "\(subject.semester)"

    cell.nameLabel.text = subject.name

    cell.semesterLabel.text = "Semester"

    cell.semesterNumberLabel.text = Semester

    return cell
}

var subjects: [Subject] = subjectsData

我现在尝试创建一个编辑功能,以便删除单元格/行,从而也删除数组中的相应项目。

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        subjectsData.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}

对我而言,代码看起来合乎逻辑且功能正常,但是当我尝试删除行/单元时运行应用程序时崩溃并收到错误:

'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

每当我删除一行/单元格时,也应删除数组中的相应项目,但如果我理解错误,那么数组似乎不会更新/删除该项目?

如果有人知道为什么会出现这种错误以及如何解决它,我将感激不尽。

1 个答案:

答案 0 :(得分:0)

好的,所以我将subjectsData.removeAtIndex(indexPath.row)更改为此editStyle代码

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        subjects.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}

因为我说var subjects: [Subject] = subjectsData

我不知道为什么这样可以解决错误,但是当我尝试删除某些内容时,应用程序现在不再崩溃。