Search code examples
iosswiftnsuserdefaults

Save an array of colors to User Defaults - iOS Swift 2.3


I am wondering how to save an array of UIColors to user default.

I have the following code to save a single UIColor to user defaults, does anyone know how to modify this to allow me to store arrays of UIColor in NS User Defaults?

extension NSUserDefaults {
    
    func colorForKey(key: String) -> UIColor? {
        var color: UIColor?
        if let colorData = dataForKey(key) {
            color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
        }
        return color
    }
    
    
    
    func setColor(color: UIColor?, forKey key: String) {
        var colorData: NSData?
        if let color = color {
            colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
        }
        setObject(colorData, forKey: key)
    }
    
}

  • I am using Swift 2.3

Solution

  • You can do it in following way

    let colors = [UIColor.whiteColor(), UIColor.greenColor()] // Array of colors
    NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(colors), forKey: "ColorsKey") //For saving in NSUserDefaults
    //For retrieving use following 
    let decodedColorsData  = NSUserDefaults.standardUserDefaults().objectForKey("ColorsKey") as! NSData
    let colorsArray = (NSKeyedUnarchiver.unarchiveObjectWithData(decodedColorsData) as! NSArray) as Array