cocos2d-x中几种存储数据的方式
说明:本文所论述内容均基于cocos2dx 3.0 版本。
1、UserDefault
它是cocos2d-x用来存取基本数据类型用的。保存为XML文件格式。
查看CCUserDefault文件,可以看出,文件名默认为UserDefault.xml。在win32平台,Debug下,该文件在Debug.win32文件夹内。如果该文件不存在,则会创建新文件。
1 // root name of xml
2 #define USERDEFAULT_ROOT_NAME "userDefaultRoot"
3
4 #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 = );
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的定义:
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定义:
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 </key>
<string>string in dictInArray value </string>
<key>string in dictInArray key </key>
<string>string in dictInArray value </string>
</dict>
<string>string in array</string>
<array>
<string>string in arrayInArray</string>
<string>string 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></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();
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=""/>
<p name="ls" age=""/>
</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<>(fu->getStringFromFile("dj.json").c_str()); // 0表示默认的解析方式;
log("%s", d[rapidjson::SizeType()]["name"].GetString());
注:需要导入cocos2d-x库 <json/document.h>
cocos2d-x中几种存储数据的方式的更多相关文章
- EntityFramework中几种更改数据的方式
首先声明个实体类,该实体类是EntityFrameWork自动生成的,对应数据表Test结构如下 public partial class Test { public int Id{ get; set ...
- Request三种获取数据的方式
今天在做ajax请求后台代码时,发现ajax的方法都对,但就是请求不了后台代码,后来在同事帮助下才发现前台定义了两个相同参数导致请求出错. 下面记录一下request三种获取数据的方式: 1. Req ...
- Spring RestTemplate中几种常见的请求方式GET请求 POST请求 PUT请求 DELETE请求
Spring RestTemplate中几种常见的请求方式 原文地址: https://blog.csdn.net/u012702547/article/details/77917939 版权声明 ...
- Spring中三种配置Bean的方式
Spring中三种配置Bean的方式分别是: 基于XML的配置方式 基于注解的配置方式 基于Java类的配置方式 一.基于XML的配置 这个很简单,所以如何使用就略掉. 二.基于注解的配置 Sprin ...
- MYSQL 4种插入数据的方式比较
4种插入数据的方式 第一种:insert into insert into是最常用的插入数据的方式,可以单条插入,也可以多条,还可以指定从其他表中select然后插入. 详细可以参考:insert语法 ...
- EntityFramework中经常使用的数据改动方式
上一篇文章里提到了 EntityFramework中经常使用的数据删除方式.那么改动对象值也有多种方式 第一种 相同是官方推荐的方式,先查询出来,再对要改动的字段赋值,这也应该是用的比較多的. 另外一 ...
- OC中两种单例实现方式
OC中两种单例实现方式 写在前面 前两天探索了一下C++ 的单例,领悟深刻了许多.今天来看看OC中的单例又是怎么回事.查看相关资料,发现在OC中一般有两种实现单例的方式,一种方式是跟C++ 中类似的常 ...
- 【转】ZYNQ中三种实现GPIO的方式
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/husipeng86/article/det ...
- android开发中的5种存储数据方式
数据存储在开发中是使用最频繁的,根据不同的情况选择不同的存储数据方式对于提高开发效率很有帮助.下面笔者在主要介绍Android平台中实现数据存储的5种方式. 1.使用SharedPreferences ...
随机推荐
- C++AMP介绍(一)
C++AMP介绍(一) 最后更新日期:2014-05-02 阅读前提: 环境:Windows 8.1 64bit英文版,Visual Studio 2013 Professional Update1英 ...
- Codeforces Round #265 (Div. 2) D. Restore Cube 立方体推断
http://codeforces.com/contest/465/problem/D 给定8个点坐标.对于每一个点来说,能够任意交换x.y,z坐标的数值. 问说8个点能否够组成立方体. 暴力枚举就可 ...
- javascript 1.5s跳转
<script type="text/javascript"> var t = 1.5; window.onload=countDown; function count ...
- eclipes设置默认注释作者
打开Perfences首选项页,搜索Template,找到Java>> Code Style >> Code Template功能,在打开的树中,找到Comments.Type ...
- component和bean区别
@Component and @Bean do two quite different things, and shouldn't be confused. @Component (and @Serv ...
- js 获取地址栏的值乱码问题
传过去的参数是:(01) 0 6936841 40029 4. 接收的参数的:'(01)%200%206936841%2040029%204'. 因为包含空格,或者中文,就会乱码.要想不乱码,接收的使 ...
- grub安装的 三种安装方式
1. 引言 grub是什么?最常态的理解,grub是一个bootloader或者是一个bootmanager,通过grub可以引导种类丰富的系统,如linux.freebsd.windows等.但一旦 ...
- Android利用温度传感器实现带动画效果的电子温度计
概述 Android利用温度传感器实现带动画效果的电子温度计. 详细 代码下载:http://www.demodashi.com/demo/10631.html 一.准备工作 需要准备一部带有温度传感 ...
- git版本库管理介绍,撤销git pull操作
Git是分布式版本控制系统,GitHub 是最大的 Git 版本库托管商,是成千上万的开发者和项目能够合作进行的中心. 大部分 Git 版本库都托管在 GitHub,很多开源项目使用 GitHub 实 ...
- Web Service——CXF+Spring 整合
结合spring框架来实现CXF发布SOAP协议的服务,步骤基本相同,所不同的是的多了一些配置项,步骤如下 1. 服务端 第一步:创建web项目(引入jar包) 第二步:创建SEI接口 import ...