ios - 在 Swift 中归档自定义对象 - 扩展

标签 ios swift nscoding user-preferences nsarchiving

我正在开发一个基于 Swift 4.0 的 iOS 应用程序。该应用程序使用第 3 方 SDK,其中有一个模型可以说,

class Customer: NSCopying, NSObject {

    var name: String!
    var age: Int!
    var address: Address!
}

那时我无法控制修改模型的任何属性和签名作为其内部 SDK。但我需要将对象存储在磁盘/用户默认值中并在需要时加载。

这可能吗?如果是,我该怎么做?

最佳答案

一种方法是使用 SwiftyJSON将模型对象转换为 JSON 数据:

extension Customer {
    func toJSON() -> JSON {
        return [
            "name": name
            "age": age
            "address": address.toJSON() // add a toJSON method the same way in an Address extension
        ]
    }

    static func fromJSON(_ json: JSON) -> Customer {
        let customer = Customer()
        customer.name = json["name"].string
        customer.age = json["age"].int
        customer.address = Address.fromJSON(json["address"]) // add a fromJSON method the same way
    }
}

现在您可以执行一些操作,例如保存到 UserDefaults

UserDefaults.standard.set(try! Customer().toJSON().rawData(), forKey: "my key")
let customer = Customer.fromJSON(JSON(data: UserDefaults.standard.data(forKey: "my key")!))

关于ios - 在 Swift 中归档自定义对象 - 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50560401/

相关文章:

ios - 非法尝试在不同上下文中的对象之间建立关系 'checklists'

ios - 应用程序 :openURL:options: not called after opening universal link

ios - RxSwift - UIImageView - 观察属性 isHighlighted

ios - PINCache objectForKey 返回 NSCoding 并且无法转换它

ios - 为 RTL 自定义 FSCalendar

iphone - iOS设备上的乐器-无法象征,因为该应用未显示在下拉菜单中

ios - 重新加载应用程序,就像它在进入前台时被杀死一样

ios - 尝试使用 NSUrl(fileURLWithPath) 捕捉

objective-c - 如何使用 NSCoding 加载 Objective C Singleton?

objective-c - setValuesForKeysWithDictionary 可以与嵌套字典一起使用吗