don*_*ile 3 iphone nsuserdefaults
我希望有一些方法可以将用户默认值备份到属性列表或XML,或者可以通过网络传输的其他一些适当的文件格式.我怎么能得到这些的备份,以便我可以将它们发送到网络服务器并将它们检索回设备并将它们读入用户默认数据库?
您可以获取用户默认值的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];
Run Code Online (Sandbox Code Playgroud)
并将它们读回设备,你可以做相反的事情:
// 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];
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息和下载链接,请查看TouchJSON项目页面.
希望有所帮助.
注意:上面的代码中没有错误检查 - 如果你的JSON包含int/float/etc,你可能会遇到问题因为setObject:forKey:会失败.
| 归档时间: |
|
| 查看次数: |
1434 次 |
| 最近记录: |