【发布时间】:2021-02-09 13:22:47
【问题描述】:
我正在尝试使用 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
}
Here is an image of what happens
内容被删除
谢谢!
【问题讨论】:
-
什么是
newdownloaditem?您需要先阅读 plist,然后添加 newItem,然后再写入。 -
@Larme
newdownloaditem是一种用于读写plist的可编码方法 -
"写入数据将删除以前的数据并替换为新数据" 您需要读取当前保存的数据,将新数据添加到其中并保存。但是我看不到您在哪里读取以前保存的数据,在哪里附加了新数据。您似乎只在前一个数据上保存(覆盖)新数据。
-
我知道,但我需要将新代码放在
下 -
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)。但是,以大写开头的类/结构命名:downloadList=>DownloadList,downloadListt是一个坏名字,最好是DownloadItem,双“t”不会产生差异.
标签: ios swift xcode cocoa plist