【发布时间】:2016-05-12 03:42:45
【问题描述】:
我在 VC 中有一个表格视图。它是使用以下代码从核心数据对象填充的:
// Variables
var allFruits: NSArray
var managedObjectContext: NSManagedObjectContext
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
func loadFruits(){
// Try to load all of the Fruits from the core data.
let fetchRequest = NSFetchRequest()
let entityDescription = NSEntityDescription.entityForName("Fruit", inManagedObjectContext: self.managedObjectContext)
fetchRequest.entity = entityDescription
do{
self.allFruits = try self.managedObjectContext.executeFetchRequest(fetchRequest)
if self.allFruits.count == 0{
print("No saved Fruits")
}
}
catch
{
let fetchError = error as NSError
print(fetchError)
}
}
然后表格视图将填充这个特定的水果数据。我有这种从表中删除水果的方法
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
// handle delete (by removing the data from your array and updating the tableview)
managedObjectContext.deleteObject(allFruits[indexPath.row] as! NSManagedObject)
// Attempt to save the object
do{
try appDelegate.managedObjectContext.save()
}
catch let error{
print("Could not save Deletion \(error)")
}
// Remove the deleted item from the table view
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// Reload the fruits
self.loadFruits()
// Reload the table view
tableView.reloadData()
}
}
每当我尝试删除水果时,这只会使应用程序崩溃。
'NSInternalInconsistencyException',原因:'无效更新:无效 第 0 节中的行数。包含在第 0 节中的行数 更新后的现有节(5)必须等于 更新前该部分中包含的行 (5),加号或减号 从该部分插入或删除的行数(0 插入, 1 已删除)并加上或减去移入或移出的行数 该部分(0 移入,0 移出)。'
我怀疑我使用NSArray 而不是NSMutableArray 这一事实存在一些问题。
我该如何解决这个问题?
提前致谢。
【问题讨论】:
标签: ios swift uitableview core-data