commitEditingStyle使我的应用程序崩溃

时间:2015-08-27 00:53:51

标签: ios swift tableview

我的应用在实施滑动删除功能时多次崩溃。

reason: 'Invalid update: invalid number of rows in section 0.  
The number of rows contained in an existing section after the update
 (1) must be equal to the number of rows contained in that section 
before the update (1), 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).'

我在某处读到这与numberOfRowsInSection处没有递减1的行有关,因此每当删除数据/行时我都会创建一个var deleted :Bool?来更改。现在,我只需轻扫并删除一次,我的应用程序在再次尝试后崩溃。

  

以下是与此相关的代码:

var myFavs : [MyFavourites]?

var deleted :Bool?



override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    if deleted == true {

        return myFavs!.count - 1
    } else {
        return (myFavs?.count)!
    }
}


// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {

        tableView.beginUpdates()

        //Delete from CD.

        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext


        let myFavo = myFavs![indexPath.row]

        context.deleteObject(myFavo as MyFavourites)

        do {
            try context.save()
        } catch _ {
        }


        // Delete the row from the data source

        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

        deleted = true

        tableView.endUpdates()
        tableView.reloadData()

    }    
}

[编辑]

我的数据源var myFavs : [MyFavourites]?是CoreData生成的NSManagedObject子类。我忘了提到当我从模拟器重新启动应用程序时,它会从coreData中成功删除。

如果有必要,请点击我的数据源代码。

extension MyFavourites {

@NSManaged var id: String?

}
  

我做错了什么?

0 个答案:

没有答案
相关问题