2016-04-23 37 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