1

我正在开发一个 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];

但是,当我这样做时,它不会将其写入文件。我只看到基于更改键值或添加到另一个键的资源。还有另一种方法可以做到这一点吗?

感谢您的时间

4

1 回答 1

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];
于 2012-08-29T04:34:11.473 回答