简体   繁体   English

将NSCountedSet保留为NSUserDefaults

[英]Persisting NSCountedSet to NSUserDefaults

I need to persist an NSCountedSet of custom objects to NSUserDefaults . 我需要将自定义对象的NSCountedSet持久NSCountedSet NSUserDefaults

I think the problem is that -(id)objectForKey: for NSUserDefaults has a special consideration in the docs here : 我认为问题在于-(id)objectForKey:对于NSUserDefaults这里的文档中有特殊考虑:

Special Considerations
The returned object is immutable, even if the value you originally set was mutable.

Question

How would I go about persisting an NSCountedSet if (as I am currently assuming?) NSUserDefaults returns a non-mutable NSSet from -(id)objectForKey: when I need to retain the internal count metadata that NSCountedSet contains? 我怎么会去坚持一个NSCountedSet如果(像我目前假设?) NSUserDefaults返回一个不可变NSSet-(id)objectForKey:当我需要保留的内部计数元NSCountedSet包含?

You can't write an NSCountedSet to user defaults. 您不能将NSCountedSet写入用户默认值。 Only arrays, dictionaries, strings, numbers, date and data. 仅数组,字典,字符串,数字,日期和数据。

You could create a dictionary matching the NSCountedSet, with the set elements as keys and the counts converted to NSNumber as values. 您可以创建一个与NSCountedSet匹配的字典,将set元素作为键,并将计数转换为NSNumber作为值。 And of course when you read the dictionary, convert it to a counted set. 当然,当您阅读字典时,请将其转换为计数集。 Just a few lines of code. 只需几行代码。

Alternatively, convert to an array with values duplicated depending on their count. 或者,将其转换为具有重复值(取决于其数量)的数组。 If the counted set contains "Hello" with a count of 3, add it to the array three times. 如果计数的集合包含计数为3的“ Hello”,请将其添加到数组中三次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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