Add key to NSDictionary (iPhone SDK)

Hey guys, really fast trying to add a key to .plist, it almost has it, what is the correct version of the fourth line? Thank!

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

almost he

in fact.

You cannot change the NSDictionary. You cannot write in 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];
+12
source

You cannot add elements to NSDictionary, you need to use NSMutableDictionary, and then use the method setObject:forKey:.

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

See NSMutableDictionary class reference

+18
source

All Articles