开发者

How to make a dump of the current NSUserDefaults standardUserDefaults state to disk and read back in?

开发者 https://www.devze.com 2023-01-01 01:04 出处:网络
I want to have some way of backing up the user defaults to a property li开发者_JS百科st or XML, or some other appropriate file format that can be transfered over the net. How could I get a backup of t

I want to have some way of backing up the user defaults to a property li开发者_JS百科st or XML, or some other appropriate file format that can be transfered over the net. How could I get a backup of these so that I can send them to a webserver and retrieve them back to the device and read them in to the user defaults database?


You can get a JSON string of the user defaults like this :

// 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];

and to read them back into the device you can just do the opposite :

// 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];

Have a look at the TouchJSON project page for more details and the download link.

Hope that helps.

NB There's no error checking in the above code - you might run into problems if your JSON contains int / float / etc because setObject:forKey: will fail.


I'd suggest either XML or JSON. Both have pretty good frameworks that ease working with them (TouchXML and TouchJSON).

0

精彩评论

暂无评论...
验证码 换一张
取 消