我正在嘗試快速將一個簡單的字典寫入 .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<Int, Int> 型別,并且僅包含 [0:0](出于簡單/故障排除的目的)。
為什么這不起作用?您有更好的將字典寫入磁盤的解決方案嗎?
uj5u.com熱心網友回復:
URL(string是錯誤的 API。它要求字串以類似的方案開頭https://。
在路徑以斜杠開頭的檔案系統中,您必須使用
let url = URL(fileURLWithPath: path)
正如WithPath所暗示的那樣。
更快捷的方法是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)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406557.html
標籤:
