How to add a key-value pair to a plist file in Objective-C

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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

回答1:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!