风言枫语  

今天白白跟大家分享一下cocos2dx中游戏的存储及需要注意的事项

cocos2dx中自带了存储类:CCUserDefault ,倘若需要存储的数据量教大的话,建议使用数据库来存储

现在先给大家看一下CCUserDefault的API

 

Public Member Functions
 
    ~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 Public Member Functions
 
static CCUserDefault *  sharedUserDefault ()
static void     purgeSharedUserDefault ()
static const std::string &  getXMLFilePath ()

 

大家可以清楚的看到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

 

注意事项:

1、写好了数据一定要记得提交,CCUserDefault会把数据存储在UserDefault.xml中,这个文件就在cocos2d-x-2.2的Debug.win32目录下。可以打开这个文件查看储存的数据。

2、key有遵循命名规则,千万不能想当然的给他随意命名,白白之前就在这上面吃过亏,希望大家谨记。

白白之前给key命名了score[i]这是不对的。

我们再来写一个例子

 

	//保存
	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[i] = CCUserDefault::sharedUserDefault()->getIntegerForKey(getScore->getCString());
		CCLOG("score[%d]:  %d", i, score[i]);
	}


ok,现在这些数据就能做为排行榜使用了

 





 

posted on 2013-11-01 18:12  风言枫语  阅读(340)  评论(0编辑  收藏  举报