简体   繁体   中英

Save custom object to NSUserDefaults

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!!

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)")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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