4bottiglie 4bottiglie - 10 months ago 65
iOS Question

NSInvalidArgumentException when setting nil UserDefaults

I am using the

to store a values into the preferences.

I have a template class and a method to get the value ( needed to be overridden )

func getValue(_ value: T?) -> Any?
return value

When i'am calling:

UserDefaults.standard.set(getValue(value), forKey: "pref_key")

can be
i get this error:

Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'Attempt to insert non-property
list object null for key pref_key'

Wasn't it supposed to remove the key if the value is nil?

Answer Source

The problem is an attempt to store a value of NSNull in UserDefaults. This isn't supported. nil is fine, it simply removes any existing value. But NSNull is not the same thing as nil.

You need to deal with this. Here's one solution:

var val = getValue(value)
if val is NSNull {
    val = nil
UserDefaults.standard.set(val, forKey: "pref_key")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download