Iphone 如何将当前NSUserDefaults standardUserDefaults状态转储到磁盘并读回?
我想用某种方法将用户的默认值备份为属性列表或XML,或者可以通过网络传输的其他适当的文件格式。我如何获得这些文件的备份,以便将它们发送到Web服务器并检索回设备,并将它们读入用户默认数据库?我建议使用XML或JSON。两者都有非常好的框架,可以轻松地使用它们(TouchXML和TouchJSON)。您可以获得如下用户默认值的JSON字符串:Iphone 如何将当前NSUserDefaults standardUserDefaults状态转储到磁盘并读回?,iphone,nsuserdefaults,Iphone,Nsuserdefaults,我想用某种方法将用户的默认值备份为属性列表或XML,或者可以通过网络传输的其他适当的文件格式。我如何获得这些文件的备份,以便将它们发送到Web服务器并检索回设备,并将它们读入用户默认数据库?我建议使用XML或JSON。两者都有非常好的框架,可以轻松地使用它们(TouchXML和TouchJSON)。您可以获得如下用户默认值的JSON字符串: // You will need this at the top of your file #import "CJSONSerializer.h" //
// 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];
//您需要将此文件放在文件顶部
#导入“CJSONDeserializer.h”
//从服务器获取数据并从中重新创建字典
NSData*jsonData=;
NSDictionary*dict=[[CJSONDeserializer反序列化器]反序列化asdictionary:jsonData错误:nil];
//将每个键放入默认值
for(在[dict allKeys]中输入id){
id object=[dict objectforKey:key];
[NSUserDefaults standardUserDefaults]设置对象:对象分叉:键];
}
[[NSUserDefaults standardUserDefaults]同步];
有关更多详细信息和下载链接,请查看
希望有帮助
注意:上面的代码中没有错误检查-如果JSON包含int/float/etc,您可能会遇到问题,因为setObject:forKey:将失败。为什么是JSON,为什么不是XML?JSON更快吗?JSON倾向于使用比XML更少的数据,但更重要的是,我以前使用过JSON:)它放松了NSDate的类型