***************************************转载请注明出处:http://blog.csdn.net/lttree********************************************
好久没有更新cocos2d-x的东西了,是在太忙,木有时间啊= =。。
1.基本概念
本篇文章是介绍,简单数据存储的Userdefault类,在API中:
就是存储一些简单的数据,比如声音的开启关闭,音效的开启关闭,最高分,金币数量的存储这些东西。
2.获取
这些都是基于一些基本类型的,比如int,float,double,bool,string,二进制 这些东西,
对于它们的存取有相应的 set和 get函数,比如:
找到Userdefault.h
bool getBoolForKey(const char* pKey);<span style="white-space:pre"> </span> int getIntegerForKey(const char* pKey); float getFloatForKey(const char* pKey); double getDoubleForKey(const char* pKey); std::string getStringForKey(const char* pKey); Data getDataForKey(const char* pKey);<span style="white-space:pre"> </span>// 二进制
bool getBoolForKey(const char* pKey, bool defaultValue);
它的含义就是,如果你通过pKey查找不到,里面没有值,你就可以让它返回defaultValue值,并且设置成defaultValue值。
其实,如果没有defaultValue也一样,只是设置并返回的是0而已:
<span style="font-family:Comic Sans MS;font-size:14px;">int UserDefault::getIntegerForKey(const char* pKey)
{
return getIntegerForKey(pKey, 0);
}
int UserDefault::getIntegerForKey(const char* pKey, int defaultValue)
{
const char* value = nullptr;
tinyxml2::XMLElement* rootNode;
tinyxml2::XMLDocument* doc;
tinyxml2::XMLElement* node;
node = getXMLNodeForKey(pKey, &rootNode, &doc);
// find the node
if (node && node->FirstChild())
{
value = (const char*)(node->FirstChild()->Value());
}
int ret = defaultValue;
if (value)
{
ret = atoi(value);
}
if(doc)
{
delete doc;
}
return ret;
}</span>
3.设置
相应的对于set来说,就很简单了,只是设置值而已。
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); void setDataForKey(const char* pKey, const Data& value);
然后就是这个flush函数了,
这个函数,话说我没怎么搞太懂,网上也众说纷纭,
API上说是 将内容保存到XML文件中,
而我查了.cpp中的定义是:
void UserDefault::flush()
{
}
5.如何使用
类的相应函数都介绍完了,接下来就是使用的问题,
首先要确定文件是否存在,不存在就初始化它:
if ( !LoadBooleanFromXML("_IS_EXISTED"))
{
initUserData();
SaveBooleanToXML("_IS_EXISTED", true);
}
CCUserDefault::sharedUserDefault()->setBoolForKey(m_Sound,true); CCUserDefault::sharedUserDefault()->getBoolForKey(m_Sound);
#define GetBool CCUserDefault::sharedUserDefault()->getBoolForKey #define SetBool CCUserDefault::sharedUserDefault()->setBoolForKey
***************************************转载请注明出处:http://blog.csdn.net/lttree********************************************
cocos2d-x 之 简单数据存储——Userdefault
原文:http://blog.csdn.net/lttree/article/details/40897789