【问题标题】:Write Dictionary to File in Swift在 Swift 中将字典写入文件
【发布时间】:2022-01-08 21:34:12
【问题描述】:

我正在尝试快速将一个简单的字典写入 .plist 文件。为方便起见,我在 Dictionary 类的扩展中编写了代码。这是它的样子。

extension Dictionary {
    func writeToPath (path: String) {
        do {
            // archive data
            let data = try NSKeyedArchiver.archivedData(withRootObject: self,
                                                    requiringSecureCoding: true)
            // write data
            do {
                let url = URL(string: path)
                try data.write(to: url!)
            }
            catch {
                print("Failed to write dictionary data to disk.")
            }
        }
        catch {
            print("Failed to archive dictionary.")
        }
    }
}

每次运行时,我都会看到“无法将字典数据写入磁盘”。路径有效。我正在使用“/var/mobile/Containers/Data/Application/(Numbers and Letters)/Documents/favDict.plist”。

字典是 Dictionary 类型,并且仅包含 [0:0](出于简单/故障排除目的)。

为什么这不起作用?您有更好的将字典写入磁盘的解决方案吗?

【问题讨论】:

  • 你能展示你是如何创建路径 url 的吗?您不能只使用硬编码路径,因为您的应用程序的沙箱具有不可预测的路径。您需要使用NSFileManager 来获取您应用的文档目录

标签: ios swift dictionary cocoa data-persistence


【解决方案1】:

URL(string 是错误的 API。它要求字符串以 https:// 之类的方案开头。

在路径以斜杠开头的文件系统中,您必须使用

let url = URL(fileURLWithPath: path)

正如 WithPath 所暗示的那样。

一个swiftier方式是PropertyListEncoder

extension Dictionary where Key: Encodable, Value: Encodable {
    func writeToURL(_ url: URL) throws {
        // archive data
        let data = try PropertyListEncoder().encode(self)
        try data.write(to: url)
    }
}

【讨论】:

  • tbf path/url/string 的区别不是特别清楚。鉴于 URL 的那部分称为路径,我可以理解为什么刚接触该平台的人会感到困惑
  • 确实是这个问题。再次被路径与网址难倒。谢谢!
  • 如果您的路径以file:// 开头,只需添加到帖子中即可使用字符串初始化程序
猜你喜欢
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2020-08-26
  • 2016-08-26
  • 1970-01-01
相关资源
最近更新 更多