简体   繁体   English

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

[英]Mac OSX How can I add plist to bundle and modify the plist

I have a plist and I copy the plist to my xcode project but it seems like the file is not in bundle: 我有一个plist,我将plist复制到我的xcode项目,但似乎文件不在bundle中:

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

but the file plist file is not showing. 但文件plist文件未显示。 Question, how can I add the file to project in a way to see in the bundle? 问题,如何以一种在捆绑中查看的方式将文件添加到项目中? also any of you knows how can I modify the plist and save the changes? 还有谁知道如何修改plist并保存更改?

I'll really appreciated your help 我真的很感激你的帮助

PS I'm using Xcode 5. PS我正在使用Xcode 5。

You can create a plist file in your bundle and modify its contents as: 您可以在捆绑中创建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);

infoDictionary will return Info.plist file. infoDictionary将返回Info.plist文件。 You should use pathForResource:ofType: method of NSBundle class. 您应该使用NSBundle类的pathForResource:ofType:方法。

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

How can I add plist to bundle 如何将plist添加到bundle中
Drag your plist to "Copy Bundle Resources" phase of your build target 将plist拖到构建目标的“Copy Bundle Resources”阶段

modify the plist 修改plist
Copy the plist to your app's Documents folder and modify it there. 将plist复制到应用程序的Documents文件夹并在那里进行修改。

this should work 这应该工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM