2016-04-23 44 views
0
func readWriteData(){ 

     let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) 
     let cachePath = paths.first 
     //  let bundleName = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String 
     let filePath = NSURL(fileURLWithPath: cachePath!).URLByAppendingPathComponent("cachedProducts.plist").path 
     var isDir : ObjCBool = false 
     var error: NSError? 
     if NSFileManager.defaultManager().fileExistsAtPath(filePath!, isDirectory: &isDir) { 
      var plistArray = NSArray(contentsOfFile: filePath!) 
      print(plistArray)//retrieving stored data 


     }else { 
      do { 
       try NSFileManager.defaultManager().createDirectoryAtPath(filePath!, withIntermediateDirectories: false, attributes: nil) 
       var cachedArray = [AnyObject]() 
       cachedArray.append("Harsh") 
       let cachedProductarray : NSArray = cachedArray 
       cachedProductarray.writeToFile(filePath!, atomically: true) 
       //Storing data to plist 


      } catch let error as NSError { 
       NSLog("\(error.localizedDescription)") 
      } 
     } 
} 

當我嘗試打印plistArray它返回零。請幫助我解決方案。我試過這個使用cachesDirectory和文檔目錄這兩個都是相同的情況讀寫陣列數據plist不工作​​

回答

0

緩存目錄應該創建在cachePath,而不是在filePath

比使用的NSArray的相當原始writeToFile方法,而我推薦使用NSPropertyListSerializationNSDatawriteToFile:options:error(猶未writeToURL...)方法一起得到有意義的錯誤消息。

+0

VAR STR:的NSString = 「ASGG」 DO { 嘗試str.writeToFile(文件路徑!原子:真,編碼:NSUTF8StringEncoding) }趕上讓誤差NSError { 打印( 「\(error.localizedDescription)」 ) } 當我試圖寫一個NSString它說 - 文件「cachedProductsssssss.plist」無法保存在文件夾「緩存」 –

+0

打印路徑,並檢查它們是否是你期望的。 – vadian