简体   繁体   中英

Store NSMutableSet to NSUserDefaults

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM