2015-09-21 1 views
1

J'ai créé un tableauEditingStyle - Enlever cellule et élément dans un tableau

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

et un 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 
} 

avec var subjects: [Subject] = subjectsData.

J'ai maintenant essayé de créer une fonction d'édition afin de supprimer des cellules/lignes et, ainsi, aussi l'élément correspondant dans le tableau.

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) 
    } 
} 

Pour moi, le code semble logique et le fonctionnement, bien que lors de l'exécution des application se bloque chaque fois que je tente de supprimer une ligne/cellule et je reçois l'erreur:

'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).'

Chaque fois que je supprime un row/cell, l'élément correspondant dans le tableau doit également être supprimé, mais si je comprends bien l'erreur, le tableau ne semble pas mettre à jour/supprimer l'élément?

Je serais reconnaissant si quelqu'un avait une idée pourquoi cette erreur se produit et comment le résoudre.

Répondre

0

Ok, donc je l'ai changé subjectsData.removeAtIndex(indexPath.row) à ce code editingStyle

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) 
    } 
} 

depuis que je dit var subjects: [Subject] = subjectsData.

Je ne sais pas pourquoi exactement cela s'est occupé de l'erreur, mais maintenant l'application ne se bloque plus, quand j'essaye de supprimer quelque chose.