doctor_ew
doctor_ew

Reputation: 123

How to add new keys to a plist?

I have a plist file with keys and values and I want the user to be able to save a key with its value so they can call it back later. I have the callback part all programmed but I need to be able to save it. Right now I have this:

- (IBAction)addKey:(id)sender {
    NSString *string1 = [input stringValue];
    NSString *string2 = [filesField stringValue];

    NSMutableDictionary *fileKeys = [[NSMutableDictionary alloc] initWithContentsOfFile:
                          [[NSBundle mainBundle] pathForResource:@"Keys" ofType:@"plist"]];
    [fileKeys setValue:string2 forKey:string1];
}

Am I doing something wrong, it doesnt add that key and its value to the plist.

Upvotes: 0

Views: 344

Answers (2)

Living Skull
Living Skull

Reputation: 136

The plist is not the only option. You could also use core data to implement it, depending on what you want to store. It comes in quite handy if you use CD, that you would be able to bind GUI controls' look to the items in CD. Basically, you would need to entities, one for the user and one for the items. This would allow yourself to keep the configuration within the bundle. Shouldn't break under sandbox, but until now I do not have any practical experience with sandboxing.

Upvotes: 0

CRD
CRD

Reputation: 53000

First you should not really be updating plist files in your bundle; while it can work it will break any signature on the application and will certainly break under the sandbox.

What you can do as an alternative is to store the original plist in your bundle and copy it to your applications Application Support folder the first time your app is run.

Second you need to write your modified dictionary back to the file system, you can do this with NSDictionary's writeToURL:atomically or writeToFile:atomically methods.

Upvotes: 2

Related Questions