2015-09-25 151 views
0

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

+0

提供有关崩溃的细节。 – rmaddy

+0

该应用程序崩溃说:'致命错误:意外发现零,同时解开一个可选值 (lldb)' – SNos

+0

在哪一行发生此错误? – rmaddy

回答

2

关于调用reloadData(),该文件说:“它不应该在插入或删除行,尤其是在与调用beginUpdates和endUpdates实现的动画块的方法调用。 “所以它能够更好地刚刚重装,你所做的更改部分,并呼吁开始,如果动画参与

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

,并结束其最好使用自己的NSFileManager实例,因为默认的只能在主线程。而且你不安全展开resultDictionary写入文件时,可能导致崩溃 PS,

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

由stringByAppendingString迅速ň2代替,仅供参考

+0

谢谢...我一直在尝试,但我得到的错误:无法用类型为'((String),withRowAnimation:UITableViewRowAnimation)'的参数列表调用'reloadRowsAtIndexPaths'' – SNos