我使用以下代码将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) ******
我的问题是,当它们存在于plist文件中时,为什么它们是(null)
?
答案 0 :(得分:2)
您正在尝试改变不可变对象。
IE
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile: path] mutableCopy];
同时检查plist对象是否为零,因为任何消息都可以发送到nil而不会出现错误。这不会失败,也没有实际发生。
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?
由于源路径为零,因此您最好不要在编译捆绑期间复制文件。把它拖到这里:
答案 1 :(得分:1)
尝试使用nsbundle资源路径
NSString *path= [[NSBundle mainBundle] pathForResource:@"SportsLogo-Info" ofType:@"plist"];
尝试分配
NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:path]];
同时检查文件是否已被复制。转到Library => Application Support => iPhone模拟器=>文件夹命名您的模拟器版本iOS => Applications =>找到您项目的正确文件夹=>文件查看plist文件是否在那里