我想有一些方法可以將用戶默認備份到屬性列表或XML,或其他可以通過網絡傳輸的適當文件格式。我怎麼能得到這些備份,以便我可以將它們發送到Web服務器並將它們檢索回設備並將它們讀入用戶默認數據庫?如何將當前NSUserDefaults standardUserDefaults狀態轉儲到磁盤並回讀?
2
A
回答
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
我會建議XML或JSON。兩者都有相當不錯的框架,可以輕鬆處理它們(TouchXML和TouchJSON)。
相關問題
- 1. NSUserDefaults:轉儲NSUserDefaults的standardUserDefaults的結構
- 2. NSUserDefaults standardUserDefaults返回零
- 3. NSUserDefaults standardUserDefaults
- 4. `[NSUserDefaults的standardUserDefaults]`返回nil
- 5. [[NSUserDefaults standardUserDefaults] objectForKey]返回什麼?
- 6. NSUserDefaults standardUserDefaults如何工作?
- 7. NSUserDefaults寫入磁盤?
- 8. 如何將對象存儲到磁盤?
- 9. 如何處理磁盤損壞/恢復磁盤損壞/恢復已將主回購恢復到舊狀態
- 10. 如何在NSUserdefaults中存儲UISegmentedControle狀態
- 11. standardUserDefaults閱讀問題
- 12. 如何將數據從redis保存到磁盤中的文件並讀回redis?
- 13. NSUserDefaults不會寫入磁盤
- 14. 存儲在磁盤上的HashMap從磁盤迴讀非常緩慢
- 15. 如何在cocos2d中使用NSUserDefaults standardUserDefaults?
- 16. 當磁盤存儲達到時sqlite3
- 17. 如何在Firefox中以當前狀態轉儲整個Web DOM?
- 18. 如何在Chrome中以當前狀態轉儲整個Web DOM?
- 19. 返回數據幀vs寫入磁盤並從磁盤讀取csv的效率
- 20. angularjs ui-router回到當前狀態
- 21. 如何將存儲過程的輸出存儲到磁盤上
- 22. 如何System.Windows.Controls.Image存儲到本地磁盤
- 23. Android是否有將應用程序狀態存儲到磁盤的方法
- 24. 將磁盤inode讀到內存中
- 25. 閱讀磁盤
- 26. Cassandra將Keyspace存儲到新磁盤
- 27. 將索引LARQ存儲到磁盤
- 28. iphone - 將圖像存儲到磁盤
- 29. 如何從「磁盤」讀取NinePatch圖像並將其轉換爲NinePatchDrawable?
- 30. 從磁盤轉儲提取jpeg
爲什麼JSON,爲什麼不是XML? JSON速度更快嗎? – dontWatchMyProfile 2010-05-27 10:06:34
JSON傾向於使用比XML更少的數據,但更重要的是,我之前使用過JSON – deanWombourne 2010-05-27 10:10:26