ios - 更新 Plist 数据而不删除旧数据
问题描述
我正在尝试使用 swift 和 cocoa 制作文件下载器应用程序。我正在使用 plist 作为下载历史记录。但是,读取数据有效,写入数据将擦除以前的数据并将其替换为新数据。
这是代码
let newdownloaditem = downloadList(root: [downloadListt(downloadURL: response.url!.absoluteString, fileName: response.suggestedFilename!)])
// This is a codeable method
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let pListFilURL = uniqueDataDir()?.appendingPathComponent("downloads.plist")
do {
let data = try encoder.encode(newdownloaditem)
try data.write(to: pListFilURL!)
// Here is the problem
} catch {
print(error)
}
// Here is the codeable
public struct downloadList: Codable {
let root: [downloadListt]
}
public struct downloadListt: Codable {
let downloadURL: String
let fileName: String
}
内容被删除
谢谢!
解决方案
您确实正在用新数据替换以前的数据。
- 您需要检索以前的数据。
- 将您的新数据附加到其中。
- 保存该组合
let newItem = downloadListt(downloadURL: response.url!.absoluteString,
fileName: response.suggestedFilename!)
var allItems: [downloadListt] = []
allItems.append(contentsOf: previousList.root)
allitems.append(newItem)
let newList = downloadList(root: allItems)
...
let data = try encoder.encode(newList)
try data.write(to: pListFilURL!)
不相关但推荐(这是约定):您应该开始用大写命名您的结构/类:downloadList
=>DownloadList
我会避免命名downloadListt
,这是不可重复的,乍一看很难区分downloadListt
and downloadList
。相反,将其命名为DownloadItem
. 更具可读性。
推荐阅读
- r - 在主题函数中更改 ggplot2 的默认参数/调色板
- r - 向量的外积加上它的转置加上一个矩阵
- python-3.x - 使用 discord py 在本地保存在 Discord 上收到的图像
- java - AES 确定性加密
- php - 如何使用 Docker 在 Alpine Linux 上部署 Laravel Web 应用程序?
- javascript - javascript中的伪数组参数
- cpu-registers - 8085微处理器中算术运算的临时寄存器需要什么?
- flash - 将 Actionscript 1 转换为 Actionscript 3
- angular - 无法使用 Windows 身份验证发布到 asp.net core web api
- vue.js - nuxt hot-reload 在虚拟机中不起作用