2010-05-27 22 views

回答

4

你可以得到用戶的默認這樣的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瞭解更多詳情和下載鏈接。

希望有所幫助。

NB上述代碼中沒有錯誤檢查 - 如果您的JSON包含int/float/etc,您可能會遇到問題,因爲setObject:forKey:將失敗。

+0

爲什麼JSON,爲什麼不是XML? JSON速度更快嗎? – dontWatchMyProfile 2010-05-27 10:06:34

+0

JSON傾向於使用比XML更少的數據,但更重要的是,我之前使用過JSON – deanWombourne 2010-05-27 10:10:26

0

我會建議XML或JSON。兩者都有相當不錯的框架,可以輕鬆處理它們(TouchXML和TouchJSON)。

相關問題