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])!
This is for Swift 3
Swift 4
Among basic types,
UserDefaults
can save any object that conforms toCodable
protocol.Dictionary
is one of the types that implements this protocol. You don't even need to write any custom code:See more info about Codable
Swift 3
You can use
UserDefaults
to save aDictionary
as long as key and value types are types that can be represented in a plist format (NSNumber
,Data
, etc.). If that's not the case, we can always serialise other types toData
when writing and deserialise fromData
when reading. It can be accomplished with pretty simple extension ofUserDefaults
usingNSKeyArchiver
:Now you can call these methods:
Swift 2
Save custom data
Retrieve data
Usage
I had a similar issue, but with different types of data. My suggestion is to convert to NSData and retrieve the data like so:
(Although it is mentioned [String : String] I actually used for [[String: AnyObject]] and worked, so maybe it can work for you too!)
if you neeed more types you can use generics like this:
For example [Int:Int] type usage: