开发者

Add key to NSDictionary (iPhone SDK)

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜