如何存储文件 cocos2dx
在Cocos2d-x中,自带了存储类 CCUserDefault。若需要存储的数据量较大,建议使用数据库进行存储。
CCUserDefault 类介绍
API 详情
公共成员函数
~CCUserDefault ();
bool getBoolForKey (const char *pKey, bool defaultValue=false);
// Get bool value by key, if the key doesn't exist, a default value will return.
int getIntegerForKey (const char *pKey, int defaultValue=0);
// Get integer value by key, if the key doesn't exist, a default value will return.
float getFloatForKey (const char *pKey, float defaultValue=0.0f);
// Get float value by key, if the key doesn't exist, a default value will return.
double getDoubleForKey (const char *pKey, double defaultValue=0.0);
// Get double value by key, if the key doesn't exist, a default value will return.
std::string getStringForKey (const char *pKey, const std::string &defaultValue="");
// Get string value by key, if the key doesn't exist, a default value will return.
void setBoolForKey (const char *pKey, bool value);
// Set bool value by key.
void setIntegerForKey (const char *pKey, int value);
// Set integer value by key.
void setFloatForKey (const char *pKey, float value);
// Set float value by key.
void setDoubleForKey (const char *pKey, double value);
// Set double value by key.
void setStringForKey (const char *pKey, const std::string &value);
// Set string value by key.
void flush ();
// Save content to xml file.
静态公共成员函数
static CCUserDefault * sharedUserDefault ();
static void purgeSharedUserDefault ();
static const std::string & getXMLFilePath ();
从上述 API 可以清晰地看到,CCUserDefault 类采用 Key - Value 的方式进行存储,通过 key 来索引 Value 的值。
使用示例
示例一:存储并获取单个数据
// 存储并获取数据
CCUserDefault::sharedUserDefault()->setStringForKey("name", "baibai");
CCUserDefault::sharedUserDefault()->flush(); // 写了东西要提交
std::string name = CCUserDefault::sharedUserDefault()->getStringForKey("name");
CCLOG("name: %s ", name.c_str());
运行上述代码后,就能打印出 name: baibai。
示例二:批量存储和获取数据
// 保存
int a[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; ++i) {
CCString* setScore = CCString::createWithFormat("a_%d", i);
CCUserDefault::sharedUserDefault()->setIntegerForKey(setScore->getCString(), a[i]);
}
CCUserDefault::sharedUserDefault()->flush(); // 提交
// 获取
for (int i = 0; i < 5; ++i) {
CCString* getScore = CCString::createWithFormat("a_%d", i);
int score = CCUserDefault::sharedUserDefault()->getIntegerForKey(getScore->getCString());
CCLOG("score[%d]: %d", i, score);
}
通过上述代码,这些数据可以作为排行榜使用。
注意事项
- 数据提交:写好数据后一定要记得提交,
CCUserDefault会将数据存储在UserDefault.xml文件中,该文件位于cocos2d-x-2.2的Debug.win32目录下,可打开此文件查看存储的数据。 - key 命名规则:key 必须遵循命名规则,不能随意命名。例如,之前将 key 命名为
score[i]是不正确的,希望大家牢记。