转自:http://blog.csdn.net/yanghuiliu/article/details/6912612java
正在作项目中有不少游戏数据要保存,常见的玩家数据这些比较简单的能够用CCUserDefault。它是cocos2d-x用来存取基本数据类型用的。保存为XML文件格式。ui
主要方法:(和java的map很像,键值对,应该很容易懂的)spa
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返回本身想要的值。.net
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);code
这样就能够生成一个xml文件。不过这种硬代码我不是很喜欢。xml
每次调用的时候要写很长的代码。能够建议搞几个宏,毕竟CCUserDefault的get,set实在太长了。blog
#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方法去获取。 get
if ( !LoadBooleanFromXML("_IS_EXISTED")) { initUserData(); SaveBooleanToXML("_IS_EXISTED", true); }