senty senty - 7 months ago 130
Swift Question

Save and Load Custom Dictionary - NSUserDefaults

I have an

[Int:Bool]
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?.

NSUserDefaults.standardUserDefaults().objectForKey("dictionary")


Then I tried this and it logged:

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


I also tried
dictionaryForKey
. I got..

NSUserDefaults.standardUserDefaults().dictionaryForKey("dictionary")



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)

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

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

Answer

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
setCustomDictionary(customDictionary)

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