【问题标题】:Swift - tableview.reloadData() crashes the appSwift - tableview.reloadData() 使应用程序崩溃
【发布时间】:2015-09-25 20:52:33
【问题描述】:

我正在从 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()

        }
    } 

【问题讨论】:

  • 提供有关崩溃的详细信息。
  • 应用程序崩溃说:'致命错误:在展开可选值 (lldb) 时意外发现 nil'
  • 这个错误发生在哪一行?
  • 请看附图
  • 尝试在该方法的第一行放置一个断点。然后,一旦程序在该断点处暂停,单步执行,直到遇到崩溃。这将告诉您哪条线路导致了崩溃。

标签: ios swift uitableview


【解决方案1】:

关于调用 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 替换,仅供参考

【讨论】:

  • 谢谢...我一直在尝试,但出现错误:无法使用类型为“((字符串),withRowAnimation:UITableViewRowAnimation)”的参数列表调用“reloadRowsAtIndexPaths”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-30
相关资源
最近更新 更多