2015-09-25 154 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