Swift - tableview.reloadData()崩溃了应用程序

时间:2015-09-25 20:52:34

标签: ios swift uitableview

我从plist中获取一些数据到UITableview中。 我试图删除所选的数据,但是当我尝试重新加载数据以显示应用程序崩溃的剩余单元格时。 我认为问题出在我使用tableview.reloadData()时,但我不确定如何解决这个问题。如果我不使用reloadData,当我重新打开视图控制器时,单元格将被删除。

任何建议?

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

                } else {
                    println("notes.plist not found")
                }


            } else {
                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()

        }
    } 

enter image description here

1 个答案:

答案 0 :(得分:3)

关于调用reloadData(),文档说:"不应该在插入或删除行的方法中调用它,特别是在通过调用beginUpdates和endUpdates实现的动画块中。"所以最好只重新加载你进行更改的部分,如果涉及动画则调用begin和end

tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths(path, withRowAnimation: UITableViewRowAnimation.Automatic)
tableView.endUpdates()

并且最好使用你自己的nsfilemanager实例,因为默认的只能在主线程中使用。并且你在写入文件时不安全地展开resultDictionary,这可能会导致崩溃 ps,

let path = DocumentDirectory.stringByAppendingPathComponent("notes.plist")

替换为stringByAppendingString n swift 2,只是fyi