繁体   English   中英

写入文档目录中的plist时出错

[英]Error writing to plist in documents directory

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

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文件中?

您正在尝试改变不可变对象。

你需要一个NSMutableDictionary

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?

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

在此输入图像描述

尝试使用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 =>查找项目的正确文件夹=>文件查看plist文件是否在那里

暂无
暂无

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

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