简体   繁体   English

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

[英]Archiving Custom Object in Swift - Extended

I am working on an iOS App on Swift 4.0. 我正在使用Swift 4.0上的iOS应用程序。 The app uses an 3rd party SDK where there is a model lets say, 该应用使用第三方软件开发工具包,其中有一个模型可以说,

class Customer: NSCopying, NSObject {

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

At that point I have no control to modify any properties and signature for the model as its inside SDK. 那时,我无法控制将模型的任何属性和签名修改为内部SDK。 But I need to store the object in disk/user defaults and load when needed. 但是我需要将对象存储在磁盘/用户默认值中,并在需要时加载。

Is it possible? 可能吗? If it is then how can I do that? 如果是,那我该怎么办?

One way is to use SwiftyJSON to convert the model object to JSON data: 一种方法是使用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
    }
}

Now you can do something like saving to UserDefaults 现在,您可以执行类似保存到UserDefaults

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM