简单数据存储 — Userdefault
基本概念
本篇文章将详细介绍用于简单数据存储的 UserDefault 类。在相关 API 中,UserDefault 类主要用于存储一些简单的数据,例如声音的开启或关闭状态、音效的开启或关闭状态、游戏的最高分以及金币数量等。
获取数据
UserDefault 类的数据存储基于一些基本数据类型,如 int、float、double、bool、string 以及二进制数据。对于这些基本类型的数据存取,UserDefault 类提供了相应的 set 和 get 函数。以下是一些常用的 get 函数示例:
bool getBoolForKey(const char* pKey);
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); // 二进制数据
上述函数中的参数 pKey 类似于一个地址,它是在设置数据时所指定的名称,通过该名称可以找到存储的数据。
此外,UserDefault 类还提供了带两个参数的 get 函数,示例如下:
bool getBoolForKey(const char* pKey, bool defaultValue);
其他类型的带双参数 get 函数与此类似,第二个参数 defaultValue 的类型会根据返回值类型而变化。其含义是,当通过 pKey 无法查找到对应的值时,函数将返回 defaultValue,并将该值设置为该 pKey 对应的值。
实际上,即使没有提供 defaultValue 参数,函数也会正常工作,只是会将 defaultValue 设置为 0。以下是 UserDefault 类中关于 int 类型的两个 get 函数的实现:
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);
// 查找节点
if (node && node->FirstChild())
{
value = (const char*)(node->FirstChild()->Value());
}
int ret = defaultValue;
if (value)
{
ret = atoi(value);
}
if(doc)
{
delete doc;
}
return ret;
}
从上述代码可以看出,没有 defaultValue 参数的 getIntegerForKey 函数实际上调用了将 defaultValue 设置为 0 的函数。
设置数据
与 get 函数相对应,UserDefault 类提供了 set 函数用于设置数据,这些函数的使用非常简单,仅用于设置值。以下是常用的 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 函数
flush 函数在 UserDefault 类中也占有重要地位,但该函数的作用在网络上存在多种说法。API 文档中指出,flush 函数的作用是将内容保存到 XML 文件中。以下是 UserDefault 类中 flush 函数的定义:
void UserDefault::flush()
{
}
在实际的游戏开发中,即使不使用 flush 函数,也可能不会出现明显的异常情况。
如何使用
在介绍完 UserDefault 类的相关函数后,接下来将介绍如何使用该类。首先,需要确定存储数据的文件是否存在,如果文件不存在,则需要对其进行初始化:
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