Search code examples
iosswiftnscodinguser-preferencesnsarchiving

Archiving Custom Object in Swift - Extended


I am working on an iOS App on Swift 4.0. 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. 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?


Solution

  • One way is to use SwiftyJSON to convert the model object to JSON data:

    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.standard.set(try! Customer().toJSON().rawData(), forKey: "my key")
    let customer = Customer.fromJSON(JSON(data: UserDefaults.standard.data(forKey: "my key")!))