Store NSMutableSet to NSUserDefaults
Asked Answered
D

1

0

I want to store a Swift Set in NSUserDefaults.

Given that I can read a NSMutableSet value from UserDefaults using:

UserDefaults.standard.mutableSetValue(forKey:)

... it seems like I should be able to write a NSMutableSet too.

I tried converting my Set to NSMutableSet, but when I try to save it in UserDefaults it says:

[User Defaults] Attempt to set a non-property-list object {( foo )} as an NSUserDefaults/CFPreferences value for key KEYNAME

Dandify answered 27/2, 2018 at 21:43 Comment(0)
D
3

mutableSetValue(forKey:) has an unfortunate name.

Most of the UserDefaults methods look very similar:

However, mutableArrayValue(forKey:) is actually coming from the NSKeyValueCoding protocol!

This protocol has methods such as:

When dealing with UserDefaults, you likely want to only use the methods from the UserDefaults list instead of the NSKeyValueCoding list.

In short, you'll want to make sure you're not looking at the NSKeyValueCoding methods, avoid trying to read/write a Set, and write a property-list object instead:

Property lists consist only of certain types of data: dictionaries, arrays, strings, numbers (integer and float), dates, binary data, and Boolean values.

Dandify answered 27/2, 2018 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.