我正在从 plist 中获取一些数据到 UITableview 中。但是,当我尝试重新加载数据以仅显示剩余的单元格时,我试图删除所选的数据,应用程序崩溃了。我认为问题出在我使用 tableview.reloadData()
时,但我不确定如何解决此问题。如果我不使用 reloadData,当我重新打开 View Controller 时,单元格将被删除。
Có gợi ý gì không?
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
let row = indexPath.row
let plistPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let DocumentsDirectory = plistPath[0] as! String
let path = DocumentsDirectory.stringByAppendingPathComponent("notes.plist")
let fileManager = NSFileManager.defaultManager()
if (!fileManager.fileExistsAtPath(path)) {
if let bundlePath = NSBundle.mainBundle().pathForResource("notes", ofType: "plist") {
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
println("Bundle notes.plist file is --> \(resultDictionary?.description)")
fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
println("copy")
} khác {
println("notes.plist not found")
}
} khác {
println("note.plist already exists")
//fileManager.removeItemAtPath(path, error: nil)
}
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
//resultDictionary?.removeAllObjects()
resultDictionary?.removeObjectForKey(allKeys[row])
resultDictionary!.writeToFile(path, atomically: false)
println("Loaded notes.plist file is --> \(resultDictionary?.description)")
tableView.reloadData()
}
}
关于调用 reloadData(),文档说:“不应在插入或删除行的方法中调用它,尤其是在通过调用 beginUpdates 和 endUpdates 实现的动画 block 中。”所以最好重新加载您进行更改的部分,如果涉及动画,则调用开始和结束
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths(path, withRowAnimation: UITableViewRowAnimation.Automatic)
tableView.endUpdates()
并且最好使用您自己的 nsfilemanager 实例,因为默认实例仅在主线程中工作。而且你在写入文件时不安全地解包 resultDictionary,这可能会导致崩溃附言,
let path = DocumentDirectory.stringByAppendingPathComponent("notes.plist")
替换为stringByAppendingString n swift 2,仅供引用
Tôi là một lập trình viên xuất sắc, rất giỏi!