sumit
7/5/2019 - 8:22 PM

Save custom class in UserDefaults

// source: http://ios-tutorial.com/how-to-save-array-of-custom-objects-to-nsuserdefaults/
// Important, for float decode using 
self.maxValue = (aDecoder.decodeFloat(forKey: Keys.maxValue.rawValue))
// not by (aDecoder.decodeObject(forKey: Keys.maxValue.rawValue) as? Float)!

class Parameter: NSObject, NSCoding {
    
//    var itemID: Int?
//    var itemName: String?
    var name = ""
    var minValue:Float = 0.0
    var maxValue:Float = 1.0
    var currentValue:Float = 0.0
    
    private enum Keys : String {
        case name = "name",
        minValue = "minValue",
        maxValue = "maxValue",
        currentValue = "currentValue"
    }
    
    init(name: String, minValue: Float, maxValue: Float, currentValue: Float)
    {
        self.name = name
        self.minValue = minValue
        self.maxValue = maxValue
        self.currentValue = currentValue
    }
    
    func encode(with aCoder: NSCoder)
    {
        aCoder.encode(self.name, forKey: Keys.name.rawValue)
        aCoder.encode(self.minValue, forKey: Keys.minValue.rawValue)
        aCoder.encode(self.maxValue, forKey: Keys.maxValue.rawValue)
        aCoder.encode(self.currentValue, forKey: Keys.currentValue.rawValue)
    }
    
    required init?(coder aDecoder: NSCoder)
    {
        self.name = (aDecoder.decodeObject(forKey: Keys.name.rawValue) as? String)!
        self.minValue = (aDecoder.decodeFloat(forKey: Keys.minValue.rawValue))
        self.maxValue = (aDecoder.decodeFloat(forKey: Keys.maxValue.rawValue))
        self.currentValue = (aDecoder.decodeFloat(forKey: Keys.currentValue.rawValue))
        
    }
    
}