Cocos2d-3.x_保存数据和读取数据

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

USING_NS_CC;


class HelloWorld : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();

	// 使用Cocos封装好的API进行写入
	void saveDataByCocosAPI();
	// 使用Cocos封装好的API进行读取
	void readDataByCocosAPI();

	// 使用自定义的API进行写入
	void saveDataByCustomAPI();
	// 使用自定义的API进行读取
	void readDataByCustomAPI();

    CREATE_FUNC(HelloWorld);
};

#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"


Scene* HelloWorld::createScene()
{
    auto scene = Scene::create();
    auto layer = HelloWorld::create();
    scene->addChild(layer);

    return scene;
}

bool HelloWorld::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

	auto sprite = Sprite::create("HelloWorld.png");
	sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x,visibleSize.height / 2 + origin.y));
	this->addChild(sprite,0);

	this->saveDataByCocosAPI();
	this->readDataByCocosAPI();

	this->saveDataByCustomAPI();
	this->readDataByCustomAPI();

    return true;
}

void HelloWorld::saveDataByCocosAPI()
{
	UserDefault::getInstance()->setBoolForKey("bool",false);
	UserDefault::getInstance()->setDoubleForKey("double",1.00f);
	UserDefault::getInstance()->setFloatForKey("float",1.0f);
	UserDefault::getInstance()->setIntegerForKey("integer",100);
	UserDefault::getInstance()->setStringForKey("string","Hello");

	UserDefault::getInstance()->flush();
}

void HelloWorld::readDataByCocosAPI()
{
	bool iBool = UserDefault::getInstance()->getBoolForKey("bool",false);
	double iDouble = UserDefault::getInstance()->getDoubleForKey("double",0.00f);
	float iFloat = UserDefault::getInstance()->getFloatForKey("float",0.0f);
	int iInteger =  UserDefault::getInstance()->getIntegerForKey("integer",0);
	std::string iString = UserDefault::getInstance()->getStringForKey("string","");

	log("iBool:%d,iDouble:%f,iFloat:%f,iInteger:%d,iString:%s",iBool,iDouble,iFloat,iInteger,iString.c_str());
}

void HelloWorld::saveDataByCustomAPI()
{
	log("%s",FileUtils::getInstance()->getWritablePath().c_str());

	auto fileUtils = FileUtils::getInstance();
	FILE *fp = fopen(fileUtils->fullPathFromRelativeFile("data.txt",fileUtils->getWritablePath()).c_str(),"w");
	fprintf(fp,"Hello World\n");
	fclose(fp);
}

void HelloWorld::readDataByCustomAPI()
{
	auto fileUtils = FileUtils::getInstance();
	std::string str = fileUtils->getStringFromFile(fileUtils->fullPathFromRelativeFile("data.txt",fileUtils->getWritablePath()));
	
	log("str:%s",str.c_str());
}

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...