Search code examples
iphoneobjective-csdknsdictionary

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 writeToFile:path atomically: YES];

Solution

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