cocos2d-x中几种存储数据的方式

转自: http://www.cnblogs.com/slysky/p/3945331.html


说明:本文所论述内容均基于cocos2dx 3.0 版本。

1、UserDefault

它是cocos2d-x用来存取基本数据类型用的。保存为XML文件格式。

查看CCUserDefault文件,可以看出,文件名默认为UserDefault.xml。在win32平台,Debug下,该文件在Debug.win32文件夹内。如果该文件不存在,则会创建新文件。

// root name of xml
#define USERDEFAULT_ROOT_NAME    "userDefaultRoot"
#define XML_FILE_NAME "UserDefault.xml"

用UserDefault

操作方式比较简单:

主要方法:(和java的map很像,键值对,应该很容易懂的)

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);

通过键读取数据,如果键不存在,可以设置一个defaultValue返回自己想要的值。

bool   getBoolForKey(const char* pKey,bool defaultValue = false);
int    getIntegerForKey(const char* pKey,int defaultValue = 0);
float  getFloatForKey(const char* pKey,float defaultValue=0.0f);
double getDoubleForKey(const char* pKey,double defaultValue=0.0);
std::string getStringForKey(const char* pKey,const std::string & defaultValue = "");

UserDefault封装了对XML文件的处理,提供了简单操作文件的方法,但是不足之处在于固定的文件夹,固定的文件名称。有限的数据类型。

2、FileUtils

static FileUtils* getInstance();//获取FileUtils类的实例

在cocos2d-x中,文件读写其实直接使用c/c++中的文件读写操作方法,但是,在实际运用中,由于移动客户端读写文件需要相应的权限,所以读写文件就需要先指定文件的路径,我们不需要获取绝对路径,只需要获取相对路径就行,因为cocos2d-x底层已经做了相应各个平台的处理.

std::string fullPathForFilename(const std::string &filename);//获取文件的完整路径

std::string getStringFromFile(const std::string& filename);//读取文件中的字符串

Data getDataFromFile(const std::string& filename);//获取文件数据

可以看下Data类:

class CC_DLL Data
{
public:
    static const Data Null;
    //构造函数
    Data();
    Data(const Data& other);
    Data(Data&& other);
    ~Data();
    // 重载符号
    Data& operator= (const Data& other);
    Data& operator= (Data&& other);

    unsigned char* getBytes() const;//获取数据
    ssize_t getSize() const;//尺寸
    void copy(unsigned char* bytes,const ssize_t size);//从bytes复制
    void fastSet(unsigned char* bytes,const ssize_t size);//从bytes快速set,使用后bytes将不能在外部使用
    void clear();//清除
    bool isNull() const;//判空
private:
    void move(Data& other);
private:
    unsigned char* _bytes;
    ssize_t _size;
};

unsigned char* getFileDataFromZip(const std::string& zipFilePath,const std::string& filename,ssize_t *size);//读取压缩文件数据(zip格式)

如果读取成功size中会返回文件的大小,否则返回0。

如果我们通过setSearchPaths()设置搜索路径("/mnt/sdcard/","internal_dir/"),然后通过setSearchResolutionsOrder()设置子区分路径("resources-ipadhd/","resources-ipad/","resources-iphonehd")。如果搜索文件名为'sprite.png' 那么会先在文件查找字典中查找key: sprite.png -> value: sprite.pvr.gz,然后搜索文件'sprite.pvr.gz'如下顺序:

/mnt/sdcard/resources-ipadhd/sprite.pvr.gz      (if not found,search next)
             /mnt/sdcard/resources-ipad/sprite.pvr.gz        (if not found,search next)
             /mnt/sdcard/resources-iphonehd/sprite.pvr.gz    (if not found,search next)
             /mnt/sdcard/sprite.pvr.gz                       (if not found,search next)
             internal_dir/resources-ipadhd/sprite.pvr.gz     (if not found,search next)
             internal_dir/resources-ipad/sprite.pvr.gz       (if not found,search next)
             internal_dir/resources-iphonehd/sprite.pvr.gz   (if not found,search next)
             internal_dir/sprite.pvr.gz                      (if not found,return "sprite.png")
 If the filename contains relative path like "gamescene/uilayer/sprite.png",and the mapping in fileLookup dictionary contains `key: gamescene/uilayer/sprite.png -> value: gamescene/uilayer/sprite.pvr.gz`.
        The file search order will be:
     	    /mnt/sdcard/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz      (if not found,search next)
     	    /mnt/sdcard/gamescene/uilayer/resources-ipad/sprite.pvr.gz        (if not found,search next)
     	    /mnt/sdcard/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz    (if not found,search next)
     	    /mnt/sdcard/gamescene/uilayer/sprite.pvr.gz                       (if not found,search next)
     	    internal_dir/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz     (if not found,search next)
     	    internal_dir/gamescene/uilayer/resources-ipad/sprite.pvr.gz       (if not found,search next)
     	    internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz   (if not found,search next)
     	    internal_dir/gamescene/uilayer/sprite.pvr.gz                      (if not found,return "gamescene/uilayer/sprite.png")
     If the new file can't be found on the file system,it will return the parameter filename directly.

如果找到返回完整路径,没找到返回'sprite.png'。

void loadFilenameLookupDictionaryFromFile(const std::string &filename);//从文件导入文件名查找字典

文件为plist格式如下:

/**
     * Loads the filenameLookup dictionary from the contents of a filename.
     * 
     * @note The plist file name should follow the format below:
     * 
     * @code
     * <?xml version="1.0" encoding="UTF-8"?>
     * <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
     * <plist version="1.0">
     * <dict>
     *     <key>filenames</key>
     *     <dict>
     *         <key>sounds/click.wav</key>
     *         <string>sounds/click.caf</string>
     *         <key>sounds/endgame.wav</key>
     *         <string>sounds/endgame.caf</string>
     *         <key>sounds/gem-0.wav</key>
     *         <string>sounds/gem-0.caf</string>
     *     </dict>
     *     <key>metadata</key>
     *     <dict>
     *         <key>version</key>
     *         <integer>1</integer>
     *     </dict>
     * </dict>
     * </plist>
     * @endcode
     * @param filename The plist file name.
     *
     @since v2.1
     * @js loadFilenameLookup
     * @lua loadFilenameLookup
     */

void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);//从ValueMap中设置文件名查找字典

ValueMap的定义:

1 typedef std::unordered_map<std::string,Value> ValueMap;

std::string fullPathFromRelativeFile(const std::string &filename,const std::string &relativeFile);//获取相对应文件的完整路径

e.g. filename: hello.png,pszRelativeFile: /User/path1/path2/hello.plist Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. )

void setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder);//设置子搜索区分路径

见fullPathForFilename()。

void addSearchResolutionsOrder(const std::string &order);//增加子搜索路径

const std::vector<std::string>& getSearchResolutionsOrder();//获取子搜索区分路径

void setSearchPaths(const std::vector<std::string>& searchPaths);//设置搜索路径

见fullPathForFilename()。

void addSearchPath(const std::string & path);//增加搜索路径

const std::vector<std::string>& getSearchPaths() const;//获取搜索路径

std::string getWritablePath();//获取一个可写入文件的路径

经过测试在win32平台上,debug版本返回的是程序文件所在的路径,release返回的是“我的文档”路径。

bool isFileExist(const std::string& filePath);//判断文件是否存在

经过测试在win32平台上,如果路径中包含中文字符会找不到文件。所以可以自己写个。

bool isAbsolutePath(const std::string& path);判断是否为绝对路径

void setPopupNotify(bool notify);

bool isPopupNotify();

Sets/Gets 当文件加载失败时弹出messagebox.

ValueMap getValueMapFromFile(const std::string& filename);//从文件获取ValueMap

bool writeToFile(ValueMap& dict,const std::string& fullPath);//写入一个ValueMap数据到plist格式文件

ValueVector getValueVectorFromFile(const std::string& filename);//从文件获取ValueVector

ValueVector定义:

1 typedef std::vector<Value> ValueVector;

函数也就这些了,还没有写demo代码,写好了贴过来。

3.SQLite

4、plist文件读写

在cocos2d-x中,对于plist文件,既可以读取,也可以进行写入的操作;下面先来看一个plist文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"/>

<plist version="1.0">
    <dict>
        <key>string element key</key>
        <string>string element value</string>
        <key>array</key>
        <array>
            <dict>
                <key>string in dictInArray key 0</key>
                <string>string in dictInArray value 0</string>
                <key>string in dictInArray key 1</key>
                <string>string in dictInArray value 1</string>
            </dict>
            <string>string in array</string>
            <array>
                <string>string 0 in arrayInArray</string>
                <string>string 1 in arrayInArray</string>
            </array>
        </array>
        <key>dictInDict,Hello World</key>
        <dict>
            <key>string in dictInDict key</key>
            <string>string in dictInDict value</string>
            <key>bool</key>
            <true/>
            <key>integer</key>
            <integer>1024</integer>
            <key>float</key>
            <real>1024.1024170</real>
            <key>double</key>
            <real>1024.1230000000000000</real>
        </dict>
    </dict>
</plist>


先不看上面的plist文件到底有些什么内容;实际上它是由下一段代码生成的。

auto root = Dictionary::create();
    auto string = String::create("string element value");
    root->setObject(string,"string element key"); // 添加一个键值对
    
    auto array = Array::create();  // 创建一个array
    
    auto dictInArray = Dictionary::create();
    dictInArray->setObject(String::create("string in dictInArray value 0"),"string in dictInArray key 0");
    dictInArray->setObject(String::create("string in dictInArray value 1"),"string in dictInArray key 1");
    array->addObject(dictInArray); // 往数组中添加一个键值对
    
    array->addObject(String::create("string in array")); // 往数组中添加一个字符串
    
    auto arrayInArray = Array::create();
    arrayInArray->addObject(String::create("string 0 in arrayInArray"));
    arrayInArray->addObject(String::create("string 1 in arrayInArray"));
    array->addObject(arrayInArray); // 往数组中添加一个数组
    
    root->setObject(array,"array");
    
    auto dictInDict = Dictionary::create();
    dictInDict->setObject(String::create("string in dictInDict value"),"string in dictInDict key");
   
    //add boolean to the plist
    auto booleanObject = Bool::create(true);
    dictInDict->setObject(booleanObject,"bool");
    
    //add interger to the plist
    auto intObject = Integer::create(1024);
    dictInDict->setObject(intObject,"integer");
    
    //add float to the plist
    auto floatObject = Float::create(1024.1024f);
    dictInDict->setObject(floatObject,"float");
    
    //add double to the plist
    auto doubleObject = Double::create(1024.123);
    dictInDict->setObject(doubleObject,"double");
    
    root->setObject(dictInDict,"dictInDict,Hello World");
// end with /
    std::string writablePath = FileUtils::getInstance()->getWritablePath();
    std::string fullPath = writablePath + "text.plist";
    if(root->writeToFile(fullPath.c_str()))
        log("see the plist file at %s",fullPath.c_str());
    else
        log("write plist file failed");
    
    // 读取上面创建的内容
    auto loadDict = __Dictionary::createWithContentsOfFile(fullPath.c_str());
    auto loadDictInDict = (__Dictionary*)loadDict->objectForKey("dictInDict,Hello World");
    auto boolValue = (__String*)loadDictInDict->objectForKey("bool");
    CCLOG("%s",boolValue->getCString());
    auto floatValue = (__String*)loadDictInDict->objectForKey("float");
    CCLOG("%s",floatValue->getCString());
    auto intValue = (__String*)loadDictInDict->objectForKey("integer");
    CCLOG("%s",intValue->getCString());
    auto doubleValue = (__String*)loadDictInDict->objectForKey("double");
    CCLOG("%s",doubleValue->getCString());


因此可以看出,对符合一定格式的plist文件,可以通过Dictionary进行操作。cocos2dx 3.0 的Dictionary,可以实现对Array,Dictionary,Integer,String,Bool等基础数据类型进行读写。

下面再来看另一种读取方式:假定plist文件如下;

<plist version="1.0">
<dict>
    <key>name</key>
    <string>Ls</string>
    <key>isgirl</key>
    <false/>
</dict>
</plist>

读取方式二,这种方法是借助VectorMap来进行读的:

FileUtils * fu = FileUtils::getInstance();
ValueMap vm = fu->getValueMapFromFile("Info.plist");
log("%s",vm["name"].asString().c_str()); // 读取string -->Ls
bool bl = vm["isgirl"].asBool(); // 读取bool -->0
log("%d",bl);

如果文件节点也是一个ValueMap,则可以通过xm["xx"].asValueMap()将节点转换为ValueMap;如果根节点为数组也可能直接通过ValueVector.getValueVectorFromFile("xx")读取数据;

5、xml文件读取

FileUtils * fu = FileUtils::getInstance();
    auto doc = new tinyxml2::XMLDocument();
    doc->Parse(fu->getStringFromFile("data.xml").c_str());
    auto root = doc->RootElement();
    for (auto e = root->FirstChildElement(); e; e = e->NextSiblingElement()) {
        std::string str;
        for (auto attr = e->FirstAttribute(); attr; attr = attr->Next()) {
            str += attr->Name();
            str += ":";
            str += attr->Value();
            str += ",";
        }
        log("%s",str.c_str());
    }

data.xml

<data>
   <p name="zs" age="23"/>
   <p name="ls" age="25"/>
</data>

上面的代码输出内容为:

cocos2d: name:zs,age:23,
cocos2d: name:ls,age:25,

注:需要导入cosos2d-x库<tinyxml2/tinyxml2.h>

6、JSON文件读取

先来看一个json : [{"name": "zs","age": 23},{"name": "ls","age": 25}]

rapidjson::Document d;
d.Parse<0>(fu->getStringFromFile("dj.json").c_str()); // 0表示默认的解析方式;
log("%s",d[rapidjson::SizeType(0)]["name"].GetString());

注:需要导入cocos2d-x库 <json/document.h>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


    本文实践自 RayWenderlich、Ali Hafizji 的文章《How To Create Dynamic Textures with CCRenderTexture in Cocos2D 2.X》,文中使用Cocos2D,我在这里使用Cocos2D-x 2.1.4进行学习和移植。在这篇文章,将会学习到如何创建实时纹理、如何用Gimp创建无缝拼接纹
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@163.com微信公众号:HopToad 欢迎转载,转载标注出处:http://blog.csdn.netotbaron/article/details/424343991.  软件准备 下载地址:http://cn.cocos2d-x.org/download 2.  简介2.1         引用C
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从Cocos2D-x官网上下载,进入网页http://www.cocos2d-x.org/download,点击Cocos2d-x以下的Download  v3.0,保存到自定义的文件夹2:从python官网上下载。进入网页https://www.python.org/downloads/,我当前下载的是3.4.0(当前最新
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发引擎,易学易用,支持多种智能移动平台。官网地址:http://cocos2d-x.org/当前版本:2.0    有很多的学习资料,在这里我只做为自己的笔记记录下来,错误之处还请指出。在VisualStudio2008平台的编译:1.下载当前稳
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《最强大脑》娱乐节目。将2048改造成一款挑战玩家对数字记忆的小游戏。邮箱:appdevzw@163.com微信公众号:HopToadAPK下载地址:http://download.csdn.net/detailotbaron/8446223源码下载地址:http://download.csdn.net/
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试以QtCreatorIDE来进行CMake构建。Cocos2d-x3.X地址:https://github.com/cocos2d/cocos2d-x1.打开QtCreator,菜单栏→"打开文件或项目...",打开cocos2d-x目录下的CMakeLists.txt文件;2.弹出CMake向导,如下图所示:设置
 下载地址:链接:https://pan.baidu.com/s/1IkQsMU6NoERAAQLcCUMcXQ提取码:p1pb下载完成后,解压进入build目录使用vs2013打开工程设置平台工具集,打开设置界面设置: 点击开始编译等待编译结束编译成功在build文件下会出现一个新文件夹Debug.win32,里面就是编译
分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net前言上次用象棋演示了cocos2dx的基本用法,但是对cocos2dx并没有作深入的讨论,这次以超级马里奥的源代码为线索,我们一起来学习超级马里奥的实
1. 圆形音量button事实上作者的本意应该是叫做“电位计button”。可是我觉得它和我们的圆形音量button非常像,所以就这么叫它吧~先看效果:好了,不多解释,本篇到此为止。(旁白: 噗。就这样结束了?)啊才怪~我们来看看代码:[cpp] viewplaincopyprint?CCContro
原文链接:http://www.cnblogs.com/physwf/archive/2013/04/26/3043912.html为了进一步深入学习贯彻Cocos2d,我们将自己写一个场景类,但我们不会走的太远,凡是都要循序渐进,哪怕只前进一点点,那也至少是前进了,总比贪多嚼不烂一头雾水的好。在上一节中我们建
2019独角兽企业重金招聘Python工程师标准>>>cocos2d2.0之后加入了一种九宫格的实现,主要作用是用来拉伸图片,这样的好处在于保留图片四个角不变形的同时,对图片中间部分进行拉伸,来满足一些控件的自适应(PS: 比如包括按钮,对话框,最直观的形象就是ios里的短信气泡了),这就要求图
原文链接:http://www.cnblogs.com/linji/p/3599478.html1.环境和工具准备Win7VS2010/2012,至于2008v2版本之后似乎就不支持了。 2.安装pythonv.2.0版本之前是用vs模板创建工程的,到vs2.2之后就改用python创建了。到python官网下载版本2.7.5的,然后
环境:ubuntu14.04adt-bundle-linux-x86_64android-ndk-r9d-linux-x86_64cocos2d-x-3.0正式版apache-ant1.9.3python2.7(ubuntu自带)加入环境变量exportANDROID_SDK_ROOT=/home/yangming/adt-bundle-linux/sdkexportPATH=${PATH}:/$ANDROID_SDK_ROOTools/export
1开发背景游戏程序设计涉及了学科中的各个方面,鉴于目的在于学习与进步,本游戏《FlappyBird》采用了两个不同的开发方式来开发本款游戏,一类直接采用win32底层API来实现,另一类采用当前火热的cocos2d-x游戏引擎来开发本游戏。2需求分析2.1数据分析本项目要开发的是一款游
原文链接:http://www.cnblogs.com/linji/p/3599912.html//纯色色块控件(锚点默认左下角)CCLayerColor*ccc=CCLayerColor::create(ccc4(255,0,0,128),200,100);//渐变色块控件CCLayerGradient*ccc=CCLayerGradient::create(ccc4(255,0,0,
原文链接:http://www.cnblogs.com/linji/p/3599488.html//载入一张图片CCSprite*leftDoor=CCSprite::create("loading/door.png");leftDoor->setAnchorPoint(ccp(1,0.5));//设置锚点为右边中心点leftDoor->setPosition(ccp(240,160));/
为了答谢广大学员对智捷课堂以及关老师的支持,现购买51CTO学院关老师的Cocos2d-x课程之一可以送智捷课堂编写图书一本(专题可以送3本)。一、Cocos2d-x课程列表:1、Cocos2d-x入门与提高视频教程__Part22、Cocos2d-x数据持久化与网络通信__Part33、Cocos2d-x架构设计与性能优化内存优
Spawn让多个action同时执行。Spawn有多种不同的create方法,最终都调用了createWithTwoActions(FiniteTimeAction*action1,FiniteTimeAction*action2)方法。createWithTwoActions调用initWithTwoActions方法:对两个action变量初始化:_one=action1;_two=action2;如果两个a
需要环境:php,luajit.昨天在cygwin上安装php和luajit环境,这真特么是一个坑。建议不要用虚拟环境安装打包环境,否则可能会出现各种莫名问题。折腾了一下午,最终将环境转向linux。其中,luajit的安装脚本已经在quick-cocos2d-x-develop/bin/中,直接luajit_install.sh即可。我的lin
v3.0相对v2.2来说,最引人注意的。应该是对触摸层级的优化。和lambda回调函数的引入(嗯嗯,不枉我改了那么多类名。话说,每次cocos2dx大更新。总要改掉一堆类名函数名)。这些特性应该有不少人研究了,所以今天说点跟图片有关的东西。v3.0在载入图片方面也有了非常大改变,仅仅只是