【问题标题】:Save NSMutable dictionary data in plist file _ integers as key将 NSMutable 字典数据保存在 plist 文件中_整数作为键
【发布时间】:2012-04-12 13:17:20
【问题描述】:

我目前正在尝试将 NSMutabledictionary 键和对象保存在 plist 文件中。我的键是整数,所以我使用 NSNumber 将它们放入 writeToFile 函数。

即使进行了更改,我也无法在 plist 查找中找到任何已保存的数据。我想 NSNumber 指针有问题,因为当我使用字符串时它可以工作。

您知道我的代码中缺少什么吗?

    NSMutableDictionary *dictionnaireNoms = [[NSMutableDictionary alloc] initWithCapacity:40];
    NSNumber *nombre = [[NSNumber alloc] initWithInteger:dictionnaireNoms.count];        
    NSString *nomCommerce = text.text;
    [dictionnaireNoms setObject:nomCommerce forKey:nombre];

    //2. Sauvegarde du nom dans un fichier
    [saveDicoCommerce enregisterNom:dictionnaireNoms];


- (void)enregisterNom:(NSMutableDictionary*)nom
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"%@", documentsDirectory);
    NSString *pathNom = [documentsDirectory stringByAppendingPathComponent:@"NomsDeCommerces.plist"];
    if (!documentsDirectory) {
        NSLog(@"Documents directory not found!");
        return;
    }
    [nom writeToFile:pathNom atomically:YES];
    if(![[NSFileManager defaultManager] fileExistsAtPath:pathNom])
    {
        NSLog(@"file not found");
        return;
    }

}

【问题讨论】:

  • 这是不可能的,因为只有 * 对象类型的数据可以保存到 nsdictionary
  • 谢谢。这是否意味着无法使用 NSMutableDictionary 将整数设置为键(例如使用其他类)?
  • 因为我在 NSMutableDictionary 的 writeToFile:Atomically 方法中发现:“此方法递归地验证所有包含的对象都是属性列表对象(NSData、NSDate、NSNumber、NSString、NSArray 或 NSDictionary 的实例) ) 在写出文件之前,如果所有对象都不是属性列表对象,则返回 NO,因为结果文件不是有效的属性列表"。

标签: iphone objective-c plist nsmutabledictionary


【解决方案1】:

NSDictionary 只能直接写自己,如果它只包含字符串键。它证实了您尝试使用

[[NSPropertyListSerialization dataWithPropertyList:nom format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil] writeToFile:pathNom atomically:NO];`

输出是:

属性列表格式无效:200(属性列表字典可能只有 CFStrings 键,而不是 'CFNumber')

但是,如果您使用 NSCoding 对其进行序列化,则可以存储包含 NSNumber 键的 NSDictionary 对象。替换这个:

[nom writeToFile:pathNom atomically:YES];

与:

[NSKeyedArchiver archiveRootObject:nom toFile:pathNom];

要读取创建的文件,请使用:

NSDictionary *nom2 = [NSKeyedUnarchiver unarchiveObjectWithFile:pathNom];

有关档案的更多信息,请参阅Archives and Serializations Programming Guide

【讨论】:

    【解决方案2】:

    你为什么要分配 NSNumber?试试这个 [your_dictionary setValue:[NSNumber numberWithInt:your_int]];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-25
      • 2018-04-05
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      相关资源
      最近更新 更多