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 时,它返回 nil。请帮我解决问题。我使用 cachesDirectory 和 Document Directory 进行了尝试,两者的情况相同
最佳答案
缓存目录应该创建在cachePath
, 不在 filePath
.
而不是使用相当原始的 writeToFile
NSArray
的方法|我建议使用 NSPropertyListSerialization
连同NSData
的 writeToFile:options:error
(更好的是 writeToURL...
)方法来获取有意义的错误消息。
关于ios - 读取将数组数据写入 plist 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36808596/