1

我使用以下代码将 Resources plist 文件复制到文档目录中:

BOOL success;
NSError *error;

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Test-Info.plist"];

success = [fileManager fileExistsAtPath:filePath];

if (!success) {
    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"Test-Info.plist"];
    success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
    NSLog(@"Test-Info.plist successfully copied to DocumentsDirectory.");
}

我收到了成功消息,这很棒。我假设它已正确复制到文档文件夹中。

但是,当我尝试读取和写入保存的 plist 文件时,它返回 null:

Test-Info.plist 中的关键条目:

Key: EnableEverything
Type: Boolean
Value: YES

编写代码:

NSString *adKey = @"EnableEverything";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"Test-Info.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];

NSString *enableEverything = [[plist valueForKey:adKey] stringValue];
NSLog(@"****** EXISTING: %@ ******", enableEverything); // returns (null)

// Disable in plist.
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?

NSString *enableEverything1 = [[plist valueForKey:adKey] stringValue];
NSLog(@"****** NOW: %@ ******", enableEverything1); // returns (null)

输出:

****** EXISTING: (null) ******
****** NOW: (null) ******

我的问题是为什么(null)它们存在于 plist 文件中?

4

2 回答 2

2

您正试图改变一个不可变的对象。

你需要一个NSMutableDictionary

IE

NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile: path] mutableCopy];

还要检查,如果 plist 对象不是 nil,因为任何消息都可以发送到 nil 而不会出现错误。这不会失败,实际上也没有发生任何事情。

[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?

由于源路径为零,因此您最喜欢在编译捆绑期间不复制文件。把它拖到这里:

在此处输入图像描述

于 2012-09-07T05:43:11.807 回答
1

试试这个资源的 nsbundle 路径

NSString *path= [[NSBundle mainBundle] pathForResource:@"SportsLogo-Info" ofType:@"plist"];

尝试分配

NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:path]];

还要检查文件是否已被复制。转到Library=>Application Support=>iPhone Simulator=>文件夹命名您的模拟器iOS版本=>Applications=>找到您项目的正确文件夹=>Documents查看plist文件是否存在

于 2012-09-07T05:59:46.250 回答