【发布时间】: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
为什么这不起作用?您有更好的将字典写入磁盘的解决方案吗?
【问题讨论】:
-
你能展示你是如何创建路径 url 的吗?您不能只使用硬编码路径,因为您的应用程序的沙箱具有不可预测的路径。您需要使用
NSFileManager来获取您应用的文档目录
标签: ios swift dictionary cocoa data-persistence