首页 > 解决方案 > 更新 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
}

这是发生的事情的图像

内容被删除

谢谢!

标签: iosswiftxcodecocoaplist

解决方案


您确实正在用新数据替换以前的数据。

  • 您需要检索以前的数据。
  • 将您的新数据附加到其中。
  • 保存该组合
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,这是不可重复的,乍一看很难区分downloadListtand downloadList。相反,将其命名为DownloadItem. 更具可读性。


推荐阅读