【问题标题】:Unable to Write Array of Dict to Plist File无法将字典数组写入 Plist 文件
【发布时间】:2018-08-25 15:32:37
【问题描述】:

我无法将字典数组写入 plist 文件。我可以将字典写入 plist 文件是可以的。

我的代码如下;总是不成功

    if var plistArray = NSMutableArray(contentsOfFile: path)
    {

        plistArray.add(dict)

        let success = plistArray.write(toFile: path, atomically: true)

        if success
        {
            print("success")
        }
        else
        {
            print("not success")
        }

    }

可能出了什么问题?

BR,

埃尔德姆

【问题讨论】:

  • 您没有提供足够的信息。您的字典包含哪些类型的对象? (plist 只能包含非常短的对象类型列表:数组、字典、字符串、日期、ints/floats/doubles/bools、Data,仅此而已。)
  • @DuncanC 它只包括你提到的原始对象类型

标签: ios swift plist nsdocumentdirectory


【解决方案1】:

首先不要在 Swift 中使用 NSMutableArray,使用原生 Swift Array

其次,不要使用 Foundation 方法在 Swift 中读写属性列表,使用PropertyListSerialization

最后,Apple 强烈建议使用 URL 相关 API 而不是 String 路径。


假设数组包含

[["name" : "foo", "id" : 1], ["name" : "bar", "id" : 2]]

使用此代码追加新项目

let url = URL(fileURLWithPath: path)

do {
    let data = try Data(contentsOf: url)
    var array = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:Any]]
    array.append(["name" : "baz", "id" : 3])
    let writeData = try PropertyListSerialization.data(fromPropertyList: array, format: .xml, options:0)
    try writeData.write(to: url)
} catch {
    print(error)
}

考虑使用Codable 协议,以便能够将符合属性列表的类和结构保存到磁盘。

【讨论】:

    【解决方案2】:

    我认为您缺少序列化部分,您需要先将您的 plist 文件转换为data,然后再写入文件。

     let pathForThePlistFile = "your plist path"
        // Extract the content of the file as NSData
        let data =  FileManager.default.contents(atPath: pathForThePlistFile)!
        // Convert the NSData to mutable array
        do{
            let array = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.MutabilityOptions.mutableContainersAndLeaves, format: nil) as! NSMutableArray
            array.add("Some Data")
            // Save to plist
            array.write(toFile: pathForThePlistFile, atomically: true)
        }catch{
            print("An error occurred while writing to plist")
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2012-07-14
      • 1970-01-01
      相关资源
      最近更新 更多