4

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?

Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256

1 Answers1

1

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")!))
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Thanks for your time. Is there any other way? The model I am using is composed of many other models and depth is also more than 2/3, It would be tedious task if I need to extend all those peach of other models :( – Sazzad Hissain Khan May 28 '18 at 07:34
  • Whichever way you use, I suspect that you must handle all the classes manually. You don't have to write an extension for every one. I mean, you can convert `Address` to JSON in `Customer.toJSON` without creating a new `Address` extension. Another way is to create `Codable` wrappers of their model classes. – Sweeper May 28 '18 at 07:38