ios - 使用 NSCoding 使用更多数组数据更新 iOS 存储的数据

标签 ios swift cocoa-touch nscoding

我有一个 ListView ,它收集用户输入表单的一些数据。

我计划为用户提供一个选项,让他们点击列表项,并记录他们点击它的日期。因此,我创建了一个 NSCoding 版本,如下所示。

class Item: NSObject, NSCoding {

    var uuid: String = NSUUID().uuidString
    var name: String = ""
    var days: [ NSDate ]?

    func encode(with coder: NSCoder) {
        coder.encode(uuid, forKey: "uuid")
        coder.encode(name, forKey: "name")
        coder.encode(days, forKey: "days")
    }

    required init?(coder aDecoder: NSCoder) {

        super.init()

        if let archivedUuid = aDecoder.decodeObject(forKey: "uuid") as? String {
            uuid = archivedUuid
        }

        if let archivedName = aDecoder.decodeObject(forKey: "name") as? String {
            name = archivedName
        }

        if let archivedDays = aDecoder.decodeObject(forKey: "days") as? [ NSDate ] {
            var getDays = archivedDays
        }

    }

    init(name: String, days: [NSDate]) {
        self.days = days
        self.name = name
        super.init()
    }

}

我想检索当前的天数列表,这将是一个数组,然后将另一个日期添加到该数组的末尾。但是,我不确定如何检索此数据并通过添加更多数据来更新数组。

我知道如何替换数据,但不更新它或使用 NSCoding 向其添加更多内容。我该如何去做呢?

最佳答案

对于任何想知道如何执行此操作(即更新数组以添加更多日期)的人 - 您只需执行此操作即可。在我的示例中,当有人单击列表中的某个项目时,我添加了更多日期,所以我这样做了 -

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let cell:UITableViewCell = tableGet.cellForRow(at: indexPath as IndexPath) as! UITableViewCell

        let cellID   = cell.tag

        if let filePath = pathForItems() {
            if (NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [Item]) != nil {
                let clickedItem = items[cellID] as? Item

                let days = clickedItem?.days ?? []
                let date = [ Date() ]
                let combinedDays = date + days
                clickedItem?.days = combinedDays
                print(clickedItem?.days)

                NSKeyedArchiver.archiveRootObject(items, toFile: filePath)

            }
        }

    }

本质上是使用 NSKeyedUnarchiver 取消归档我的数据,从该数据中获取数组,然后向该特定数组添加更多内容。将其全部压缩备份,然后将其放回存储中。

实际上并不太难。

关于ios - 使用 NSCoding 使用更多数组数据更新 iOS 存储的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55109562/

相关文章:

swift - "public"在 Swift 中意味着什么?

ios - Appstore 审核人员会允许我们在 iOS8 中使用动态库吗?

iOS 11 无法禁用复制粘贴选项 UITextField

ios - 将请求数据从 UIPageViewController 传递到 subview

ios - 从 Firebase 更新或删除数据时数组索引出错

ios - ARKit——Xcode 9 Beta 6 中的错误

ios - 如何在模糊效果之上有一个 UIPageView?

iphone - View XIB 和空 XIB 之间有什么区别?

ios - lexicontext ios sdk是否在utf8中提供自动完成

ios - 新的 RealmSwift 0.95.0 带来了三个编译器警告