iPhone - 将NSMutableDictionary写入文件 [英] iPhone - Writing NSMutableDictionary to file

查看:147
本文介绍了iPhone - 将NSMutableDictionary写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将可变字典写入文件时遇到了麻烦。这是我正在编写的代码。
我正在读取如下文件:(第一次运行app时,它将没有任何数据)

I'm having trouble in writing mutable dictionary to a file. Here's the code that I'm writing. I'm reading the file like below: (first time when app is ran, it won't have any data)

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
self.favSaveFilePath = [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"Favorites.plist"]];
if([fm fileExistsAtPath:favSaveFilePath])
{
    favoriteJokesDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:self.favSaveFilePath];
    favoriteJokes = [[NSMutableArray alloc] initWithArray:[self.favoriteJokesDictionary objectForKey:@"FavoriteJokes"]];
    return;
}

我正在将新字典添加到数组中,如下所示:

I'm adding new dictionary to array as below:

-(BOOL)addJokeToFavorite:(NSDictionary*)joke
{
    BOOL success = NO;
    [self.favoriteJokes addObject:joke];
    success = [self.favoriteJokesDictionary writeToFile:self.favSaveFilePath atomically:YES];
    return success;
}

我不知道为什么它不会把字典弄错。任何人都可以指出我正在做的错误吗?

I don't know why its not wring the dictionary to file. Can any one point me the mistake that I'm doing?

推荐答案

Cocoa API非常具体,可以指出哪种值可以在写入文件时合法地在字典中。已知导致问题并且在官方API文档中未详细讨论的一个特定限制是,字典中的所有键必须是NSString类型(并且您的值必须是NSData,NSDate,NSNumber,NSString之一) ,NSArray或NSDictionary),即使字典本身支持任何对象类型的键和值。

The Cocoa API is very specific about what kind of values can legally be in a dictionary when it is written out to file. One particular limitation that has been known to cause problems and which is not thoroughly discussed in the official API documentation is that all of the keys in your dictionary must be of type NSString (and your values must be one of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary), even though the dictionary itself supports keys and values of any object type.

此限制的原因与字典存储为XML文档(或属性列表,在Apple-speak中)默认情况有关。因此,我建议验证您的字典是否符合要保存到文件的要求,如果没有,则重新构建它。

The reason for this restriction has to do with the fact that the dictionary gets stored as an XML document (or "property-list", in Apple-speak) by default. So I'd recommend verifying that your dictionary meets the requirements to be saved to file, and restructuring it if it doesn't.

或者,如果重组字典不是可行的,你可能想看一下 NSKeyedArchiver 类。

Or, if restructuring your dictionary is not feasible, you might want to take a look at the NSKeyedArchiver class instead.

这篇关于iPhone - 将NSMutableDictionary写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆