为什么NSMutableDictionary不想写入文件?

Igo*_*iuc 4 iphone nsfilemanager nsmutabledictionary ios

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[NSFileManager defaultManager] fileExistsAtPath:pathString]) 
    {
        infoDict = [[NSMutableDictionary alloc] initWithContentsOfFile:pathString];
    } 
    else 
    {
        infoDict = [[NSMutableDictionary alloc]initWithObjects:[NSArray arrayWithObjects:@"BeginFrame",@"EndFrame", nil] forKeys:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil]];
        if ([infoDict writeToFile:pathString atomically:YES])
        {
            NSLog(@"Created");
        } 
        else 
        {
            NSLog(@"Is not created");
            NSLog(@"Path %@",pathString);
        }
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码.我检查文件是否已创建,如果没有 - 我创建了一个NSMutableDictionary并将其写入文件路径,但 writeToFile方法返回NO.哪里有问题?如果我用NSFileManager 它创建这个文件是有效的,但是当我想写一个字典时却没有.

Fre*_*ung 29

writeToFile:atomically仅当您调用它的字典是有效的属性列表对象时才有效(请参阅docs).

要使a NSDictionary成为有效的属性列表对象,除其他外,其键必须是字符串,但在您的示例中,键是NSNumber实例.

  • 谢谢!我刚刚被所有键必须是字符串的要求绊倒了. (3认同)

Bri*_*ian 12

您有时无法控制要写入的内容.例如,null当您要编写从服务器获取的JSON对象时,您无法避免使用某个值.

NSData与这些"无效"值兼容,因此在这些情况下转换NSArrayNSDictionary转换NSData是理想的方式.

写:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:jsonObject];
[data writeToFile:path atomically:YES];
Run Code Online (Sandbox Code Playgroud)

读:

NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *jsonObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Run Code Online (Sandbox Code Playgroud)