用cocos2dx默认的方式存放数据是不安全的,通常要经过base64编码
新建工程,testCode
修改HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::CCLayer
{
public:
// Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)
virtual bool init();
// there's no 'id' in cpp, so we recommend to return the class instance pointer
static cocos2d::CCScene* scene();
// preprocessor macro for "static create()" constructor ( node() deprecated )
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "BaseData.h"
using namespace cocos2d;
using namespace CocosDenshion;
using namespace std;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
//需要存储的字符串
string sValue="Himi";
//将对存储的数据进行编码
string saveBaseString = saveData(sValue.c_str(),sValue.length());
//将得到编码后的数据进行存储
CCUserDefault::sharedUserDefault()->setStringForKey("Base", saveBaseString);
CCUserDefault::sharedUserDefault()->flush();
//从存储中获取编码的数据
string loadBaseString = CCUserDefault::sharedUserDefault()->getStringForKey("Base");
//对编码数据进行解码得到真实数据
string trueValue=parseData(loadBaseString);
//---------用以观察数据
CCLabelTTF *label=CCLabelTTF::create("","Helvetica",20);
label->setPosition(ccp(240,185));
addChild(label);
string logStr="编码前的数据";
logStr+=sValue;
logStr+=" 编码后的数据:";
logStr+=saveBaseString;
label->setString(logStr.c_str());
CCLabelTTF *label2=CCLabelTTF::create("","Helvetica",20);
label2->setPosition(ccp(240,140));
addChild(label2);
logStr="解码前的数据";
logStr+=loadBaseString;
logStr+=" 解码后的数据:";
logStr+=trueValue;
label2->setString(logStr.c_str());
return true;
}