Mac OSX 如何将 plist 添加到 bundle 并修改 plist

3

我有一个plist文件,将其复制到我的xcode项目中,但似乎文件不在bundle中:

NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
nslog (@"dict %@",dict);

但是plist文件没有显示出来。问题是,我该如何将文件添加到项目中以便在bundle中看到?还有,你们中的任何人知道如何修改plist并保存更改吗?
非常感谢您的帮助。
附注:我正在使用Xcode 5。

你想在你的 bundle 上写入 plist 文件吗? - Hussain Shabbir
你是在询问如何通过编程方式修改plist文件吗? - markhunte
3个回答

4
您可以在应用程序包中创建一个 plist 文件,并修改其内容,如下所示:
NSString *bundlePath = [[NSBundle mainBundle]bundlePath]; //Path of your bundle
NSString *path = [bundlePath stringByAppendingPathComponent:@"MyPlist.plist"]; 
NSFileManager *fileManager = [NSFileManager defaultManager];

NSMutableDictionary *data;

if ([fileManager fileExistsAtPath: path]) 
{
    data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];  // if file exist at path initialise your dictionary with its data
}
else
{
    // If the file doesn’t exist, create an empty dictionary
    data = [[NSMutableDictionary alloc] init];
}

//To insert the data into the plist
int value = 5;
[data setObject:[NSNumber numberWithInt:value] forKey:@"value"];
[data writeToFile: path atomically:YES];
[data release];

//To retrieve the data from the plist
NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
int savedValue;
savedValue = [[savedData objectForKey:@"value"] intValue];
NSLog(@"%i",savedValue);

2

infoDictionary 将返回 Info.plist 文件。 您应该使用 NSBundle 类的 pathForResource:ofType: 方法。

NSString *commonDictionaryPath;
if (commonDictionaryPath = [[NSBundle mainBundle] pathForResource:@"CommonDictionary" ofType:@"plist"])  {
    theDictionary = [[NSDictionary alloc] initWithContentsOfFile:commonDictionaryPath];
}

如何将plist添加到bundle中
将您的plist拖到构建目标的“复制Bundle资源”阶段中

修改plist
将plist复制到您的应用程序文档文件夹中并在那里进行修改。


0

这应该可以工作

     NSString*pListDictPath = [[NSBundle mainBundle] pathForResource:@"yourPlistName" ofType:@"plist" inDirectory:@"YourDirectory"];
     if()
     {
            NSDictionary *theDictionary = [[NSDictionary alloc] initWithContentsOfFile:pListDictPath ];
     }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接