更改 NSUserDefaults 中的对象,无需创建和重新设置副本
我的字典存储在 NSUserDefaults
中,我需要添加/删除该字典中的项目。
让我困扰的是,要做到这一点,我必须创建整个字典的可变副本,更改一个元素并用新副本替换整个字典。
copy = [[defaults objectForKey:@"foo"] mutableCopy];
[copy setObject:… forKey:@"bar"];
[defaults setObject:copy forKey:@"foo"];
它涉及对层次结构中更深层次的对象进行更多的复制和重新设置。
有没有更好的办法?
我尝试使用 [defaults setValue:… forKeyPath:@"foo.bar"]
但这似乎不起作用(对象不可变)。
I've got dictionary stored in NSUserDefaults
and I need to add/remove items in this dictionary.
It bothers me that to do this I have to create mutable copy of entire dictionary, change one element and replace entire dictionary with new copy.
copy = [[defaults objectForKey:@"foo"] mutableCopy];
[copy setObject:… forKey:@"bar"];
[defaults setObject:copy forKey:@"foo"];
and it involves even more copying and re-setting for objects deeper in the hierarchy.
Is there a better way?
I've tried to use [defaults setValue:… forKeyPath:@"foo.bar"]
but that doesn't seem to work (object is not mutable).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通常创建一个自定义类来保存我的所有应用程序首选项。 该类可以在程序启动时加载 userDefaults 的可变副本一次,然后处理整个过程中的所有增量保存:
MyPreferences.h
MyPreferences.m
我创建在我的应用程序委托中创建此类的实例,然后在应用程序启动时调用
[myPrefs load]
。 程序运行时更改的任何首选项都可以通过myPrefs
进行修改,然后根据需要调用[myPrefs save]
进行保存:作为额外的好处,您可以构建 < code>MyPreferences 可以按照您喜欢的方式进行类,将 OO 编程的优势引入到整套首选项中。 我在这里展示了简单的方法,只需使用可变字典,但您可以将每个首选项放入一个属性中,并对更复杂的对象(例如 NSColor 等)进行预处理/后处理。
I usually create a custom class to hold all of my application preferences. That class can load mutable copies of the userDefaults once, when the program starts, and then handle all of the incremental saves along the way:
MyPreferences.h
MyPreferences.m
I create an instance of this class in my application delegate and then call
[myPrefs load]
when my application launches. Any preferences changed while the program is running can be modified throughmyPrefs
, and then saved by calling[myPrefs save]
as desired:As an added bonus, you can structure the
MyPreferences
class any way you like, bringing the benefits of OO programming to the whole set of preferences. I showed the easy way here, simply using a mutable dictionary, but you can make each preference into a property, and do pre/post processing for more complicated objects likeNSColor
, for instance.