我有一个plist文件,将其复制到我的xcode项目中,但似乎文件不在bundle中:
NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
nslog (@"dict %@",dict);
但是plist文件没有显示出来。问题是,我该如何将文件添加到项目中以便在bundle中看到?还有,你们中的任何人知道如何修改plist并保存更改吗?
非常感谢您的帮助。
附注:我正在使用Xcode 5。
我有一个plist文件,将其复制到我的xcode项目中,但似乎文件不在bundle中:
NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
nslog (@"dict %@",dict);
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
将返回 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复制到您的应用程序文档文件夹中并在那里进行修改。
这应该可以工作
NSString*pListDictPath = [[NSBundle mainBundle] pathForResource:@"yourPlistName" ofType:@"plist" inDirectory:@"YourDirectory"];
if()
{
NSDictionary *theDictionary = [[NSDictionary alloc] initWithContentsOfFile:pListDictPath ];
}