Mac OSX如何添加plist以捆绑和修改plist

时间:2013-10-27 06:20:38

标签: objective-c xcode macos

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

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

但文件plist文件未显示。问题,如何以一种在捆绑中查看的方式将文件添加到项目中?还有谁知道如何修改plist并保存更改?

我真的很感激你的帮助

P.S。我正在使用Xcode 5。

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

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

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

如何添加plist到捆绑
将plist拖到构建目标的“Copy Bundle Resources”阶段

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

答案 2 :(得分:0)

这应该有效

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