4bottiglie 4bottiglie - 2 months ago 22
iOS Question

NSInvalidArgumentException when setting nil UserDefaults

I am using the

UserDefaults
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")


where
value
can be
nil
,
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")