将 NSDictionary 写入我的应用程序包中的 plist

发布于 2024-08-27 00:42:30 字数 630 浏览 6 评论 0原文

我正在尝试将 NSDictionary 写入 plist,但是当我打开 plist 时,没有数据写入其中。 从日志来看,我的路径看起来是正确的,并且我的代码非常标准。 有什么想法吗?

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", @"value3", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

NSString *path = [[NSBundle mainBundle] pathForResource:@"FormData" ofType:@"plist"];
NSLog(@"path:%@", path);

[dictionary writeToFile:path atomically:YES];

I'm trying to write an NSDictionary to a plist but when I open the plist no data has been written to it.
From the log my path looks correct and my code is pretty standard.
Any ideas?

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", @"value3", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

NSString *path = [[NSBundle mainBundle] pathForResource:@"FormData" ofType:@"plist"];
NSLog(@"path:%@", path);

[dictionary writeToFile:path atomically:YES];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逆夏时光 2024-09-03 00:42:30

约翰是对的——你不能修改你的应用程序包。对于保存词典的位置,您有两个不错的选择:文档目录,当用户同步其设备时由 iTunes 备份;或缓存目录,该目录未备份。如果您不需要备份数据,请将其放入缓存中,这样就不会减慢同步速度。您可以像这样获取目录路径:

NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *cachesDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];

Johan is right -- you're not allowed to modify your app's bundle. You have two good options for where to save your dictionary: the documents directory, which is backed up by iTunes when a user syncs their device; or the caches directory, which is not backed up. If you don't need to have the data backed up, put it in caches so you don't slow down syncing. You can get the directory paths like so:

NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *cachesDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
野侃 2024-09-03 00:42:30

它不会被保存,因为您无法写入应用程序的包中。将文件保存在其他位置,例如文档文件夹中。

It doesn't get saved because you can't write into your app's bundle. Save your file elsewhere, in the documents folder for example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文