简体   繁体   English

将密钥添加到 NSDictionary (iPhone SDK)

[英]Add key to NSDictionary (iPhone SDK)

A really quickly trying to add a key to a .plist.非常快速地尝试向 .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];

You can't add elements to a NSDictionary, you need to use a NSMutableDictionary then use the setObject:forKey: method.您不能向 NSDictionary 添加元素,您需要使用 NSMutableDictionary 然后使用setObject:forKey:方法。

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

See NSMutableDictionary class reference请参阅NSMutableDictionary 类参考

almost have it几乎拥有它

not really.并不真地。

You can't change a NSDictionary.您不能更改 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];

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

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