开发者

Add key to NSDictionary (iPhone SDK)

开发者 https://www.devze.com 2023-02-14 05:40 出处:网络
A really quickly trying to add a key to a .plist. I almost have it, what is the correct version of the fourth line?

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 writeToFi开发者_运维百科le:path atomically: YES];


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


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消