iphone - 如何在Objective-C中将键值对添加到plist文件

标签 iphone objective-c ios

我正在使用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];

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

感谢您的时间

最佳答案

您无法在捆绑包中进行任何更改。因此,您要做的就是将.plist文件复制到您的documents目录中,并在那里进行操作。

遵循以下原则:

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

关于iphone - 如何在Objective-C中将键值对添加到plist文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12170871/

相关文章:

objective-c - 获取用于更改空间的 key

iphone - 如何添加下拉列表?

iphone - objective-c - 如何将 nsdata 转换为字节数组

objective-c - 如何使 Swift 类在 XPC 服务中可用?

ios - 为什么不将所有@properties 声明为strong 并将它们设为nil?

iphone - 固定 View Controller 的方向

ios - UIImageView 不动

ios - 如何快速保存钥匙串(keychain)中的名称和密码详细信息

iphone - UINavigationController:推自己?

基于 iPhone View 的应用程序没有核心数据?