ios - 读取将数组数据写入 plist 不起作用

标签 ios plist

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连同NSDatawriteToFile:options:error (更好的是 writeToURL... )方法来获取有意义的错误消息。

关于ios - 读取将数组数据写入 plist 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36808596/

相关文章:

iphone - 创建地址簿副本

objective-c - 如果当前语言不存在本地化版本,如何加载默认语言 plist?

ios - xcode 验证错误 : The info. plist 文件缺少所需的 key :CFBundleVersion

ios - Swift:将 oldArray[][] 复制到 newArray[][] 会导致错误(类型 'Any' 没有下标成员)

objective-c - 保存、文档扩展名和首选项 (Info.plist)

ios - 如何获取同一 Apple ID 上所有 Apple 设备的位置

ios - 在 .podspec 文件中包含一个私有(private) pod 作为另一个私有(private) pod 的依赖项

ios - 分配时的内存泄漏

ios - UINavigationController pushviewcontroller 内存管理

ios - 主观 iPhone/Core 数据设置民意调查