如何将当前NSUserDefaults standardUserDefaults状态转储到磁盘并重新读入?

时间:2010-05-27 09:37:43

标签: iphone nsuserdefaults

我希望有一些方法可以将用户默认值备份到属性列表或XML,或者可以通过网络传输的其他一些适当的文件格式。我怎么能得到这些备份,以便我可以将它们发送到网络服务器并将它们检索回设备并将它们读入用户默认数据库?

2 个答案:

答案 0 :(得分:5)

您可以获取用户默认值的JSON字符串,如下所示:

// You will need this at the top of your file
#import "CJSONSerializer.h"


// Get a dictionary of the user defaults
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];

// Convert them to JSON
NSString *json = [[CJSONSerializer serializer] serializeObject:dictionary];

要将它们读回设备,你可以反其道而行:

// You will need this at the top of your file
#import "CJSONDeserializer.h"

// Get the data from the server and re-create the dictionary from it
NSData *jsonData = <YOUR DATA FROM THE SERVER>;
NSDictionary *dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:nil];

// Put each key into NSUserDefaults
for (id key in [dict allKeys]) {
    id object = [dict objectforKey:key];
    [NSUserDefaults standardUserDefaults] setObject:object forKey:key];
}
[[NSUserDefaults standardUserDefaults] synchronize];

请查看TouchJSON project page了解更多详情和下载链接。

希望有所帮助。

注意:上面的代码中没有错误检查 - 如果你的JSON包含int / float / etc,你可能会遇到问题,因为setObject:forKey:会失败。

答案 1 :(得分:0)

我建议使用XML或JSON。两者都有非常好的框架,可以轻松使用它们(TouchXML和TouchJSON)。