iOS Notes 29: How to save Dictionary in UserDefaults?

Kuray Ogun
FreakyCoder Software Blog

--

Updated: April 16, 2020

Using a dictionary is awesome and very easy but it is hard to save in UserDefaults. Definitely Apple should rework on it.

Code:

func saveDictionary(dict: Dictionary<Int, String>, key: String){
let preferences = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: dict)
preferences.set(encodedData, forKey: key)
// Checking the preference is saved or not
didSave(preferences: preferences)
}

func getDictionary(key: String) -> Dictionary<Int, String> {
let preferences = UserDefaults.standard
if preferences.object(forKey: key) != nil{
let decoded = preferences.object(forKey: key) as! Data
let decodedDict = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! Dictionary<Int, String>

return decodedDict
} else {
let emptyDict = Dictionary<Int, String>()
return emptyDict
}
}

Gist:

We simply convert our dictionary to Data object via NSKeyedArchiever and decode our data via NSKeyedUnachiever. If you’re a newbie on iOS, this might look confusing but just try to use it and trace it. You will figure it out your own and you will never forget that :)

Extra Info 1: You can use your own Custom Models to save in your UserDefaults via this method.

Extra Info 2: You can save Arrays via this method.

If you have any question, ask me :)

--

--