【问题标题】:Update plist - swift更新 plist - 快速
【发布时间】:2015-01-24 00:53:53
【问题描述】:

我的应用中有一个 .plist,用于保存重要数据。它分为以下层次结构:

  1. 列表项
  2. 根 - 字典
  3. 设置 - 字典
    1. 设置 1 - 数组
    2. 设置 2 - 数组

如何将数据写入 3.1 和 3.2 数组?我只是将数据添加到 3. 数组中,仅此而已。我使用以下代码读取数据,效果很好:

if let path = NSBundle.mainBundle().pathForResource("SettingsList", ofType: "plist") {
    if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> {
        //   println(dict[settings!][setting1, String])

        settingsArray = dict[settings!]![setting1!] as Array

        println(settingsArray)
    }
}

【问题讨论】:

    标签: ios arrays dictionary plist


    【解决方案1】:

    您应该使用可变字典而不是字典。更新字典的数据,完成后,使用 writeToFile 方法将可变字典写入文件:

    func writeToFile(_ path: String, atomically atomically: Bool) -> Bool
    

    根据您的代码,您应该:

    1. 更改此行:if let dict = NSDictionary(contentsOfFile: path) as? Dictionary&lt;String, AnyObject&gt; 以制作可变字典:let dict = NSMutableDictionary(contentsOfFile: path)
    2. 更新它
    3. 将其写入您的文件:dict?.writeToFile(path, atomically: true)

    【讨论】:

    • 仅仅将 NSDictionary(contentsOfFile: path) 更改为 NSMutableDictionary(contentsOfFile: path) 为我做到了。谢谢阿里
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2015-11-01
    相关资源
    最近更新 更多