为什么当我在tableview中删除一行时,它会删除多行?
问题描述:
我正在做一个笔记应用程序,并添加了滑动删除行方法。我遇到的问题是当表格视图中保存了多个笔记,并且我滑动一行以删除它时会删除所有笔记。另外,当我退出应用程序并返回时,便签又回到桌子视图中。下面是我的代码:为什么当我在tableview中删除一行时,它会删除多行?
class MasterViewController: UITableViewController {
var notesItems: NSMutableArray = NSMutableArray()
override func viewDidAppear(animated: Bool) {
let userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let itemListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("itemList") as? NSMutableArray
if ((itemListFromUserDefaults) != nil) {
notesItems = itemListFromUserDefaults!
}
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.toolbarHidden = false
self.tableView.dataSource = self
UINavigationBar.appearance().barTintColor = UIColor.orangeColor()
UIToolbar.appearance().barTintColor = UIColor.orangeColor()
}
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notesItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let notesItem:NSDictionary = notesItems.objectAtIndex(indexPath.row) as! NSDictionary
cell.textLabel?.text = notesItem.objectForKey("text") as? String
return cell
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
self.tableView.reloadData()
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
// Delete the row from the data source
}
}
}
答
您在commitEditingStyle
中的代码都是错误的。
- 请勿重新加载表格视图。
- 在致电
deleteRowsAtIndexPaths
之前,您必须更新数据库。 - 您无需致电
beginUpdates/endUpdated
即可致电deleteRowsAtIndexPaths
。
你想:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
// remove an object from notesItem for this index path
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
@maddy我得到这个错误:终止应用程序由于未捕获的异常“NSInternalInconsistencyException”,理由是:“无效的更新:行数量无效在部分0中的行数包含在更新(7)之后的现有部分中必须等于更新前(7)中包含在该部分中的行数,加上或减去从该部分插入或删除的行数(0插入,1删除)并加上或减去移入或移出该部分的行数(0移入,0移出)。 – coding22
您未更新数据源。将代码中的注释替换为实际代码以更新数据源。 – rmaddy
我这样做notesItems.removeObjectAtIndex(indexPath.row),我得到一个错误说:NSInternalInconsistencyException',原因:' - [__ NSCFArray removeObjectAtIndex:]:发送到不可变对象的变异方法' – coding22