如果数据类型不可变,如何重写 plist?
我越来越习惯使用 plist 来初始化我的应用程序。我现在想将应用程序状态保存回用于初始化应用程序的 plist,但我发现自己陷入了困境。在应用程序启动时,我将 plist 提取到不可变的 NSDictionary 中。我现在想通过用现有键的新值替换旧值来更新 NSDictionary,并通过 [NSDictionary writeToFile:atomically] 写入 plist。如何解决 NSDictionary 的不变性?
谢谢, Doug
更新 - 还没有完全实现,
我按照 zneak 的建议将我的设置文件提取到 NSMutableDictionary 中。工作正常。在写出 plist 之前,我确认新值现在取代了旧值。凉爽的。很好,可以走了。
问题:当我这样编写文件时:
if ([self.settings writeToFile:plistPath atomically:YES] == NO) {
NSLog(@"Unable to write plist");
}
该方法愉快地正确完成 - 条件是“是”而不是“否” - 但我没有看到文件。文件去哪儿了?
我不应该在目录树中看到新文件吗?
I am getting comfortable with using plists for initializing my app. I now want to save app state back to the plist used to initialize the app and I find myself stuck. At application startup I ingest the plist into an NSDictionary which is immutable. I now want to update the NSDictionary by replacing old values with new values for existing keys and write to the plist via [NSDictionary writeToFile:atomically]. How do I get around the immutability of NSDictionary?
Thanks,
Doug
UPDATE - Not quite there yet
I followed zneak's suggestion and ingested my settings file into an NSMutableDictionary. Works fine. Prior to writing the plist out I confirm that new values now replace old values. Cool. Good to go.
Problem: when I write the file thusly:
if ([self.settings writeToFile:plistPath atomically:YES] == NO) {
NSLog(@"Unable to write plist");
}
The method happily completes properly - the conditional is YES rather then NO - but I see no file. Where has the file gone?
Shouldn't I see the new file in my directory tree?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过调用
-[myDict mutableCopy]
将其设为NSMutableDictionary
,然后使用它来写入文件;或者简单地使用[NSMutableDictionary DictionaryWithContentsOfFile:(NSString*)]
加载 plist 来获取一个可变实例而不是不可变实例。Make it a
NSMutableDictionary
by calling-[myDict mutableCopy]
, then use this one for writing the file; or simply load the plist using[NSMutableDictionary dictionaryWithContentsOfFile:(NSString*)]
to get a mutable instance to start with instead of an immutable one.使用
NSMutableDictionary
(您可以使用-[NSDictionary mutableCopy]
创建它)。然后,您可以像使用NSDictionary
一样使用writeToFile
。Use an
NSMutableDictionary
(you can use-[NSDictionary mutableCopy]
to create it). You can then usewriteToFile
just as with anNSDictionary
.