如何在Objective-C中将键值对添加到plist文件 [英] How to add a key-value pair to a plist file in Objective-C

查看:83
本文介绍了如何在Objective-C中将键值对添加到plist文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用iPhone应用程序,需要使用Objective-C将新的键值对添加到现有的plist文件中.到目前为止,这是我尝试过的:

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?

谢谢您的时间

推荐答案

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

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.

遵循以下原则:

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

这篇关于如何在Objective-C中将键值对添加到plist文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆