0

I want to save my object into NSUserDefaults.

here is my Model:

 class User: SafeJson {
    var email: String?
    var name: String?
} 

SafeJson:

  class SafeJson: NSObject {

    override func setValue(_ value: Any?, forKey key: String) {

        let uppercasedFirstCharacter = String(key.first!).uppercased()
        let range = NSMakeRange(0, 1)
        let selectorString = NSString(string: key).replacingCharacters(in: range, with: uppercasedFirstCharacter)

        let selector = NSSelectorFromString("set\(selectorString):")
        let responds = self.responds(to: selector)

        if !responds {
            print("\n\n\n*******--->\(selector) key is missing in API response...<---*******\n\n\n")
            return
        }

        super.setValue(value, forKey: key)
    }
} 

Created UserObj by this:

let UserObj = User()
UserObj.setValuesForKeys(responseOfAPI)    

now I want to save UserObj to NSUserDefaults but don't know how to do...

and I don't want to use required init(coder aDecoder: NSCoder) and func encode(with aCoder: NSCoder) in my model class because there are so many properties of User Model.

thanks!!

Uday Babariya
  • 1,031
  • 1
  • 13
  • 31
  • please see: https://stackoverflow.com/search?q=Save+custom+object+to+NSUserDefaults there are lots of similar questions that have already been answered – Scriptable Jun 04 '18 at 14:47
  • Possible duplicate of [How to store custom objects in NSUserDefaults](https://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults) – Scriptable Jun 04 '18 at 14:48

1 Answers1

0

You cannot serialize objects to UserDefaults, generally.

However, since you're working with JSON, you can use the Codable type to translate the object to/from JSON for storage.

[*] One caveat is that Any isn't Codable. The simplest way to make a type codable is to declare its properties using types that are already Codable. These types include standard library types like String, Int, and Double; and Foundation types like Date, Data, and URL. Any type whose properties are codable automatically conforms to Codable just by declaring that conformance.

Here's a simplified example:

//: Playground - noun: a place where people can play

import UIKit

class SafeJson: Codable {
    var strValues:[String:String] = [:]
    var intValues:[String:Int] = [:]

    func setValue(_ value: String?, forKey key: String) {
        strValues[key] = value
    }

    func setValue(_ value: Int?, forKey key: String) {
        intValues[key] = value
    }
}

let encoder = JSONEncoder()
let decoder = JSONDecoder()

let sampleObject = SafeJson()
sampleObject.setValue(12, forKey: "intValue1")
sampleObject.setValue(12345, forKey: "intValue2")
sampleObject.setValue("Banana", forKey: "yellowFruit1")
sampleObject.setValue("Orange", forKey: "orangeFruit1")

let encoded = try encoder.encode(sampleObject)
let key = "encodedObj"
UserDefaults.standard.setValue(encoded, forKey: key)


if let readValue = UserDefaults.standard.value(forKey: key) as? Data {
    let decodedObj = try decoder.decode(SafeJson.self, from: readValue)
    print("Decoded to \(decodedObj)")
}
David S.
  • 6,567
  • 1
  • 25
  • 45