将密钥添加到 NSDictionary (iPhone SDK)

发布于 2024-10-19 14:26:14 字数 341 浏览 3 评论 0原文

非常快速地尝试将密钥添加到 .plist。我差不多明白了,第四行的正确版本是什么?

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
    NSDictionary *rootDict = [[NSDictionary alloc] initWithContentsOfFile:path];
    [rootDict addKey:@"Test"]; //guessed code
    [rootDict writeToFile:path atomically: YES];

A really quickly trying to add a key to a .plist. I almost have it, what is the correct version of the fourth line?

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
    NSDictionary *rootDict = [[NSDictionary alloc] initWithContentsOfFile:path];
    [rootDict addKey:@"Test"]; //guessed code
    [rootDict writeToFile:path atomically: YES];

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

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

发布评论

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

评论(2

病毒体 2024-10-26 14:26:14

您无法向 NSDictionary 添加元素,您需要使用 NSMutableDictionary,然后使用 setObject:forKey: 方法。

[rootDict setObject:someObject forKey:@"someKey"];

请参阅 NSMutableDictionary 类参考

You can't add elements to a NSDictionary, you need to use a NSMutableDictionary then use the setObject:forKey: method.

[rootDict setObject:someObject forKey:@"someKey"];

See NSMutableDictionary class reference

心在旅行 2024-10-26 14:26:14

差不多了

您无法更改 NSDictionary。您无法写入主包。


工作代码:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[rootDict setObject:@"Test" forKey:@"Key"];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Favourites.plist"];
[rootDict writeToFile:writablePath atomically: YES];
[rootDict release];

almost have it

not really.

You can't change a NSDictionary. You can't write to the mainbundle.


working code:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[rootDict setObject:@"Test" forKey:@"Key"];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Favourites.plist"];
[rootDict writeToFile:writablePath atomically: YES];
[rootDict release];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文