0
votes

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?

1
Are you return nil or NSNull from your getValue method? - rmaddy
nil, but some values may be NSNull, wasn't it supposed to support both? - 4bottiglie
No, you can't store NSNull in UserDefaults. - rmaddy

1 Answers

2
votes

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