>我目前正在尝试将NSMutable字典键和对象保存在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
只有在只包含字符串键的情况下才能直接写入自身。 它确认了您尝试使用
[[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];
有关存档的详细信息,请参阅存档和序列化编程指南。
分配NSNumber?试试这个 [your_dictionary setValue:[NSNumber numberWithInt:your_int]];