轉自:http://blog.csdn.net/yanghuiliu/article/details/6912612
正在做項目中有很多游戲數據要保存,常見的玩家數據這些比較簡單的可以用CCUserDefault。它是cocos2d-x用來存取基本數據類型用的。保存為XML文件格式。
主要方法:(和java的map很像,鍵值對,應該很容易懂的)
void setBoolForKey(const char* pKey, bool value); void setIntegerForKey(const char* pKey, int value); void setFloatForKey(const char* pKey, float value); void setDoubleForKey(const char* pKey, double value); void setStringForKey(const char* pKey, const std::string & value);
通過鍵讀取數據,如果鍵不存在,可以設置一個defaultValue返回自己想要的值。
bool getBoolForKey(const char* pKey, bool defaultValue = false); int getIntegerForKey(const char* pKey, int defaultValue = 0); float getFloatForKey(const char* pKey, float defaultValue=0.0f); double getDoubleForKey(const char* pKey, double defaultValue=0.0); std::string getStringForKey(const char* pKey, const std::string & defaultValue = "");
首次運行程序時可以去生成xml文件CCUserDefault::sharedUserDefault()->setIntegerForKey("MyGold", 0);
這樣就可以生成一個xml文件。不過這種硬代碼我不是很喜歡。
每次調用的時候要寫很長的代碼。可以建議搞幾個宏,畢竟CCUserDefault的get,set實在太長了。
#define SaveStringToXML CCUserDefault::sharedUserDefault()->setStringForKey #define SaveIntegerToXML CCUserDefault::sharedUserDefault()->setIntegerForKey #define SaveBooleanToXML CCUserDefault::sharedUserDefault()->setBoolForKey #define LoadStringFromXML CCUserDefault::sharedUserDefault()->getStringForKey #define LoadIntegerFromXML CCUserDefault::sharedUserDefault()->getIntegerForKey #define LoadBooleanFromXML CCUserDefault::sharedUserDefault()->getBoolForKey
如何首次生成判斷文件是否存在呢
其實可以利用get方法去獲取。
if ( !LoadBooleanFromXML("_IS_EXISTED")) { initUserData(); SaveBooleanToXML("_IS_EXISTED", true); }