I'm working on an iPhone app and I need to add a new key-value pair to an existing plist file using objective-c. This is what I've tried so far:
NSString *myFile=[[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"]; dict = [[NSMutableDictionary alloc] initWithContentsOfFile:myFile]; [dict setObject:textContent forKey:keyName]; [dict writeToFile:myFile atomically:YES];
However, when I do this it doesn't write it to the file. I've only seen resources based on either changing the value of a key or adding to another key. Is there another way to accomplish this?
Thank you for your time
You cannot make any changes in the bundle. So what you have to do is copy the .plist
file into your documents directory and do the manipulation there.
Something along these lines:
//check for plist //Get documents directory's location NSArray*docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString*filePath=[docDir objectAtIndex:0]; NSString*plistPath=[filePath stringByAppendingPathComponent:@"Favourites.plist"]; //Check plist's existance using FileManager NSError*err=nil; NSFileManager*fManager=[NSFileManager defaultManager]; if(![fManager fileExistsAtPath:plistPath]) { //file doesn't exist, copy file from bundle to documents directory NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"]; [fManager copyItemAtPath:bundlePath toPath:plistPath error:&err]; } //Get the dictionary from the plist's path NSMutableDictionary*plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; //Manipulate the dictionary [plistDict setObject:textContent forKey:keyName]; //Again save in doc directory. [plistDict writeToFile:myFile atomically:YES];