Store NSMutableSet to NSUserDefaults

心已入冬 提交于 2019-12-13 03:37:12

问题


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


回答1:


mutableSetValue(forKey:) has an unfortunate name.

Most of the UserDefaults methods look very similar:

  • array(forKey:)
  • bool(forKey:)
  • dictionary(forKey:)
  • object(forKey:)
  • set(_:forKey:)

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

This protocol has methods such as:

  • mutableArrayValue(forKey:)
  • mutableSetValue(forKey:)
  • value(forKey:)
  • setValue(_:forKey:)

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.



来源:https://stackoverflow.com/questions/49018416/store-nsmutableset-to-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!