1

How to fix exception:

[User Defaults] Attempt to set a non-property-list object {
4 = 5;
} as an NSUserDefaults/CFPreferences value for key MyKey

thrown by executing following code (Swift 3)

let ns = NSDictionary(dictionary: [4: 5])
UserDefaults.standard.set(ns, forKey: "MyKey")

Code above correctly saves String type, but has problem with NSDictionary

Hamish
  • 78,605
  • 19
  • 187
  • 280
zgorawski
  • 2,597
  • 4
  • 30
  • 43
  • 1
    Check this question: https://stackoverflow.com/questions/37825630/save-dictionary-in-userdefaults-in-swift-3-with-xcode-8 – Max Pevsner Jun 07 '17 at 14:19

2 Answers2

4

All property list keys are required to be String.

From the documentation

And 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.

let ns = ["4": 5]
UserDefaults.standard.set(ns, forKey: "MyKey")

No need to use NSDictionary, Swift Dictionary works the same way and is implicitly bridged.

vadian
  • 274,689
  • 30
  • 353
  • 361
2

Your dictionary must have strings as keys for you to be able to save it to UserDefaults

this works for me:

let ns = NSDictionary(dictionary: ["4": 5])
UserDefaults.standard.set(ns, forKey: "MyKey")
SveinnV
  • 184
  • 4