我当前正在尝试将NSMutabledictionary密钥和对象保存在plist文件中。我的键是整数,所以我使用NSNumber将它们放入writeToFile函数中。
即使做了这样的更改,我也无法在plist find中找到我保存的任何数据。我认为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;
}
}发布于 2012-04-12 22:42:37
仅当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。
发布于 2012-04-12 22:30:46
为什么要分配NSNumber?尝试此[your_dictionary setValue:NSNumber numberWithInt:your_int];
https://stackoverflow.com/questions/10124397
复制相似问题