我正在使用iPhone应用,我需要使用objective-c为现有的plist文件添加新的键值对。这是我到目前为止所尝试的:
NSString *myFile=[[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
dict = [[NSMutableDictionary alloc] initWithContentsOfFile:myFile];
[dict setObject:textContent forKey:keyName];
[dict writeToFile:myFile atomically:YES];
但是,当我这样做时,它不会将其写入文件。我只看到基于更改密钥值或添加到另一个密钥的资源。还有另一种方法可以实现这个目标吗?
感谢您的时间
答案 0 :(得分:3)
您无法对捆绑包进行任何更改。因此,您需要做的是将.plist
文件复制到文档目录中并在那里进行操作。
这些方面的东西:
//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];