senty senty - 1 year ago 197
Swift Question

Save and Load Custom Dictionary - NSUserDefaults

I have an

dictionary and I am trying to save it into my NSDictionary.. However, it crashes with error
Attempt to set a non-property-list object

let dictionary = [Int:Bool]()

self.dictionary[2] = true
self.dictionary[3] = false

NSUserDefaults.standardUserDefaults().setObject(dictionary, forKey: "dictionary")

Also, for loading, first I tried this but error logged it strictly requires AnyObject?.


Then I tried this and it logged:

NSUserDefaults.standardUserDefaults().objectForKey("dictionary") as? [Int:Bool]

I also tried
. I got..


Cannot assign value to type [String: AnyObject] to type [Int:Bool]

So which one of these 2 is a better approach to take? (The values would be optional in my case I think)

NSUserDefaults.standardUserDefaults().objectForKey("dictionary") as? [Int:Bool] ?? [Int:Bool]()

NSUserDefaults.standardUserDefaults().objectForKey("dictionary") as? [Int:Bool])!

Answer Source

You can't add custom dictionaries to NSUserDefaults like that because NSUserDefaults only accepts NS like objects like NSArray or NSDictionary. Still you can set your [Int: Bool] dictionary by archiving it to NSData using NSKeyedArchiver.

func setCustomDictionary(dict: [Int: Bool]) {
    let keyedArch = NSKeyedArchiver.archivedDataWithRootObject(dict)

    NSUserDefaults.standardUserDefaults().setObject(keyedArch, forKey: "dictionary")

and to get the data use this function:

func getDictionary() -> [Int: Bool]? {
    let data = NSUserDefaults.standardUserDefaults().objectForKey("dict")
    let object = NSKeyedUnarchiver.unarchiveObjectWithData(data as! NSData)
    return object as? [Int: Bool]

And the example:

var customDictionary = [Int: Bool]()
customDictionary[2] = true
customDictionary[3] = false

// Store data in NSUserDefaults

// Get data from NSUserDefaults
let userDefaultsDictionary = getDictionary()