0

I'm trying to save a dictionary to NSUserDefaults using the setObject() function but when I use the objectForKey() function to retrieve the dictionary it returns nil. Why is this happening?

var data = NSUserDefaults.standardUserDefaults();
var scoreboard = [Int : String]()
let scores = "scoresKey"

scoreboard[3] = "spencer"
scoreboard[6] = "brooke"
scoreboard[11] = "jason"

data.setObject(scoreboard, forKey: scores)
data.objectForKey(scores) // Returns nil
spencer.sm
  • 19,173
  • 10
  • 77
  • 88

1 Answers1

1

The first problem was that it's not possible to use NSUserDefaults in a Playground.

See: https://stackoverflow.com/a/31210205/3498950

A second problem is found when the code above runs in a normal iOS project. It throws an NSInvalidArgumentException since the dictionary was a non-property list object because the keys needed to be of type String.

Although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

See: "What is a Property List?" in the Apple Docs

Community
  • 1
  • 1
spencer.sm
  • 19,173
  • 10
  • 77
  • 88
  • Did you try the exact code above? It doesn't work for me. It throws an exception: "Attempt to set a non-property-list object { 6 = brooke; 3 = spencer; 11 = jason; } as an NSUserDefaults/CFPreferences value for key scoresKey". – Kurt Revis May 02 '16 at 06:55
  • 1
    (Which is because "property-list" dictionaries must have strings as keys. See ["What is a property list?"](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html#//apple_ref/doc/uid/10000048i-CH3-54303) in the Apple docs, and also [this question](http://stackoverflow.com/questions/22704678/nsdictionary-with-nsnumber-to-nsstring-mapping-is-non-property-list-object).) – Kurt Revis May 02 '16 at 07:05