|   版权声明:本文为博主原创文章,未经博主允许不得转载。

FileUtils

在游戏中,用户要保存自己的偏好设置和玩家的信息,都需要涉及到游戏数据的处理。首先要想处理数据,则要找到文件,创建文件,读写文件...;在Cocos2d-x中有一个类FileUtils,FileUtils是Cocos2d-x引擎中封装的一个简单的文件操作类,该类几乎实现了所有文件操作的功能,类FileUtils并不只是一个文件,也不是两个文件。在每个平台都会有一个FileUtils的头文件和实现文件。在游戏的开始阶段,游戏的文件资源一般都是存放在硬盘中,在游戏开始的时候,文件操作模块就会将硬盘中的资源转移到内存中。

在游戏中文件的读取分为三个部分:

1. 资源存放在硬盘中

2. 资源存放在内存中

3. 资源存放在缓存中

API常用函数介绍:

 /**  Gets the instance of FileUtils.获得文件模块的单例对象 */
static FileUtils* getInstance();
/** Destroys the instance of FileUtils.释放文件模块*/
static void destroyInstance();
/** 清空缓存
* Purges full path caches.
*/
virtual void purgeCachedEntries();
/** 从文件中获取字符串。
* Gets string from a file.
*/
virtual std::string getStringFromFile(const std::string& filename);
/** 获得资源文件的内容
* Creates binary data from a file.
* @return A data object.
*/
virtual Data getDataFromFile(const std::string& filename);
/** 获取资源文件数据
* Gets resource file data
* @param[in] filename The resource file name which contains the path.
* @param[in] mode The read mode of the file.
* @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
* @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned.
*/
CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t *size);
/** 从zip文件中获得资源文件的内容
* Gets resource file data from a zip file.
* @param[in] filename The resource file name which contains the relative path of the zip file.
* @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
* @return Upon success, a pointer to the data is returned, otherwise nullptr.
* @warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned.
*/
virtual unsigned char* getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size);
/** 获得一个文件的绝对路径,返回值为文件的绝对路径(通过文件名查找文件,并将它所在的路径返回)
* Returns the fullpath for a given filename.
*/
virtual std::string fullPathForFilename(const std::string &filename) const;
/** 通过一个文件名在字典容器中查找文件
* Loads the filenameLookup dictionary from the contents of a filename.
* @note The plist file name should follow the format below:
*/
virtual void loadFilenameLookupDictionaryFromFile(const std::string &filename);
/** 设置一个按文件名查找的字典。
* Sets the filenameLookup dictionary.
* @param pFilenameLookupDict The dictionary for replacing filename.
*/
virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);
/** 获得一个文件的绝对路径包含文件名
* Gets full path from a file name and the path of the relative file.
*/
virtual std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile);
/** 设置数组容器内所包含的资源的搜索顺序。
* Sets the array that contains the search order of the resources.
* @param searchResolutionsOrder The source array that contains the search order of the resources.
* @see getSearchResolutionsOrder(), fullPathForFilename(const char*).
*/
virtual void setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder);
/** 追加资源的搜索顺序。
* Append search order of the resources.
* @see setSearchResolutionsOrder(), fullPathForFilename().
*/
virtual void addSearchResolutionsOrder(const std::string &order,const bool front=false);
/** 获取数组中所包含的资源的搜索顺序
* Gets the array that contains the search order of the resources.
* @see setSearchResolutionsOrder(const std::vector<std::string>&), fullPathForFilename(const char*).
*/
virtual const std::vector<std::string>& getSearchResolutionsOrder() const;
/** 设置资源路径
* Sets the array of search paths.
*/
virtual void setSearchPaths(const std::vector<std::string>& searchPaths);
/** 设置默认资源的根路径。
* Set default resource root path.
*/
void setDefaultResourceRootPath(const std::string& path);
/** 添加搜索路径。
* Add search path.
*/
void addSearchPath(const std::string & path, const bool front=false);
/** 获取的搜索路径的数组。
* Gets the array of search paths.
*/
virtual const std::vector<std::string>& getSearchPaths() const;
/** 获取可写的路径。
* Gets the writable path.
* @return The path that can be write/read a file in
*/
virtual std::string getWritablePath() const = ;
/** 设置可写的路径。
* Sets writable path.
*/
virtual void setWritablePath(const std::string& writablePath);
/** 设置在无法加载图像时候是否弹出一个消息框。
* Sets whether to pop-up a message box when failed to load an image.
*/
virtual void setPopupNotify(bool notify);
/** 检查在无法加载图像的时候是否弹出一个消息框。
* Checks whether to pop up a message box when failed to load an image.
* @return True if pop up a message box when failed to load an image, false if not.
*/
virtual bool isPopupNotify() const;
/** 文件到ValueMap的内容转换。(将文件中的内容转换成ValueMap类型)
* Converts the contents of a file to a ValueMap.
* @param filename The filename of the file to gets content.
* @return ValueMap of the file contents.
* @note This method is used internally.
*/
virtual ValueMap getValueMapFromFile(const std::string& filename);
/** Converts the contents of a file to a ValueMap.
* This method is used internally.
*/
virtual ValueMap getValueMapFromData(const char* filedata, int filesize);
/** 写一个内容为ValueMap类型的plist文件
* write a ValueMap into a plist file
*@param dict the ValueMap want to save
*@param fullPath The full path to the file you want to save a string
*@return bool
*/
virtual bool writeToFile(ValueMap& dict, const std::string& fullPath);
/** 写一个内容为String类型的.plist文件
* write a string into a file
* @param dataStr the string want to save
* @param fullPath The full path to the file you want to save a string
* @return bool True if write success
*/
virtual bool writeStringToFile(std::string dataStr, const std::string& fullPath);
/**
* write Data into a file
*@param retData the data want to save
*@param fullPath The full path to the file you want to save a string
*@return bool
*/
virtual bool writeDataToFile(Data retData, const std::string& fullPath);
/**
* write ValueMap into a plist file
*@param dict the ValueMap want to save
*@param fullPath The full path to the file you want to save a string
*@return bool
*/
virtual bool writeValueMapToFile(ValueMap& dict, const std::string& fullPath);
/**
* write ValueVector into a plist file
*@param vecData the ValueVector want to save
*@param fullPath The full path to the file you want to save a string
*@return bool
*/
virtual bool writeValueVectorToFile(ValueVector vecData, const std::string& fullPath);
/**
* Windows fopen can't support UTF-8 filename
* Need convert all parameters fopen and other 3rd-party libs
* @param filename std::string name file for conversion from utf-8
* @return std::string ansi filename in current locale
*/
virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const;
// Converts the contents of a file to a ValueVector.
// This method is used internally.
virtual ValueVector getValueVectorFromFile(const std::string& filename);
/** 判断文件是否存在
* Checks whether a file exists.
* @note If a relative path was passed in, it will be inserted a default root path at the beginning.
* @param filename The path of the file, it could be a relative or absolute path.
* @return True if the file exists, false if not.
*/
virtual bool isFileExist(const std::string& filename) const;
/** 获取文件的扩展名是在较低的情况下的后缀(由点从基本文件名隔开)。
* Gets filename extension is a suffix (separated from the base filename by a dot) in lower case.
* Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt.
* @param filePath The path of the file, it could be a relative or absolute path.
* @return suffix for filename in lower case or empty if a dot not found.
*/
virtual std::string getFileExtension(const std::string& filePath) const;
/** 检查路径是否是绝对路径。
* Checks whether the path is an absolute path.t.
*/
virtual bool isAbsolutePath(const std::string& path) const;
/**检查路径是否是一个目录。
* Checks whether the path is a directory.
* @param dirPath The path of the directory, it could be a relative or an absolute path.
* @return True if the directory exists, false if not.
*/
virtual bool isDirectoryExist(const std::string& dirPath) const;
/** 创建一个字典目录
* Creates a directory.
* @param dirPath The path of the directory, it must be an absolute path.
* @return True if the directory have been created successfully, false if not.
*/
virtual bool createDirectory(const std::string& dirPath);
/** 移除一个目录
* Removes a directory.
* @param dirPath The full path of the directory, it must be an absolute path.
* @return True if the directory have been removed successfully, false if not.
*/
virtual bool removeDirectory(const std::string& dirPath);
/** 移除一个文件
* Removes a file.
* @param filepath The full path of the file, it must be an absolute path.
* @return True if the file have been removed successfully, false if not.
*/
virtual bool removeFile(const std::string &filepath);
/** 给指定目录下的文件重命名
* Renames a file under the given directory.
* @param path The parent directory path of the file, it must be an absolute path.
* @param oldname The current name of the file.
* @param name The new name of the file.
* @return True if the file have been renamed successfully, false if not.
*/
virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name);
/** 给指定目录下的文件重命名
* Renames a file under the given directory.
* @param oldfullpath The current fullpath of the file. Includes path and name.
* @param newfullpath The new fullpath of the file. Includes path and name.
* @return True if the file have been renamed successfully, false if not.
*/ virtual bool renameFile(const std::string &oldfullpath, const std::string &newfullpath);
/** 检索文件的大小
* Retrieve the file size.
* @note If a relative path was passed in, it will be inserted a default root path at the beginning.
* @param filepath The path of the file, it could be a relative or absolute path.
* @return The file size.
*/
virtual long getFileSize(const std::string &filepath);
/** 返回的完整路径缓存。
* Returns the full path cache.
*/
const std::unordered_map<std::string, std::string>& getFullPathCache() const { return _fullPathCache; } protected CONUT: /** 在字典中使用一个文件的密钥来查找文件名
* Dictionary used to lookup filenames based on a key.
* It is used internally by the following methods:基于下面的方法在内部使用
* std::string fullPathForFilename(const char*);
*/
ValueMap _filenameLookupDict;
/** 该Vector容器包含有分辨率文件夹。元素在此向量的低指数,该决议目录优先级越高。
* The vector contains resolution folders.
* The lower index of the element in this vector, the higher priority for this resolution directory.
*/
std::vector<std::string> _searchResolutionsOrderArray;
/**Vector容器包含的搜索路径。
* The vector contains search paths.
* The lower index of the element in this vector, the higher priority for this search path.
*/
std::vector<std::string> _searchPathArray;
/** 资源的默认根路径。
* The default root path of resources.
* If the default root path of resources needs to be changed, do it in the `init` method of FileUtils's subclass.
* For instance:
* On Android, the default root path of resources will be assigned with "assets/" in FileUtilsAndroid::init().
* Similarly on Blackberry, we assign "app/native/Resources/" to this variable in FileUtilsBlackberry::init().
*/
std::string _defaultResRootPath;
/** 完整路径缓存。当一个文件被发现,它将被添加到该高速缓存。
* The full path cache. When a file is found, it will be added into this cache.
* This variable is used for improving the performance of file search.
*/
mutable std::unordered_map<std::string, std::string> _fullPathCache;
/**可写路径。
* Writable path.
*/
std::string _writablePath;
/** 文件实用的单指针。
* The singleton pointer of FileUtils.
*/
static FileUtils* s_sharedFileUtils;

实例:

.h files

#ifndef _FILEUTILSTEST_SCENE_H_
#define _FILEUTILSTEST_SCENE_H_
#include "cocos2d.h"
class fileUtil : public cocos2d::Layer
{
private:
public:
static cocos2d::Scene* createScene();
virtual bool init();
void fileUtil::testResolutionDirectories(Ref* sender);
void fileUtil::testSearchPath(Ref* sender);
void fileUtil::testFilenameLookup(Ref* sender);
void fileUtil::testIsFileExist(Ref* sender);
void fileUtil::testWritePlist(Ref* sender);
CREATE_FUNC(fileUtil);
};
#endif // _FILEUTILSTEST_SCENE_H_ .cpp files #include "fileUtilsTest.h" USING_NS_CC; Scene* fileUtil::createScene()
{
auto scene = Scene::create();
auto layer = fileUtil::create();
scene->addChild(layer);
return scene;
} bool fileUtil::init()
{
if (!Layer::init())
{
return false;
} Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto item1 = MenuItemFont::create("testResolutionDirectories", CC_CALLBACK_1(fileUtil::testResolutionDirectories, this));
auto item2 = MenuItemFont::create("testSearchPath", CC_CALLBACK_1(fileUtil::testSearchPath, this));
auto item3 = MenuItemFont::create("testFilenameLookup", CC_CALLBACK_1(fileUtil::testFilenameLookup, this));
auto item4 = MenuItemFont::create("testIsFileExist", CC_CALLBACK_1(fileUtil::testIsFileExist, this));
auto item5 = MenuItemFont::create("testWritePlist", CC_CALLBACK_1(fileUtil::testWritePlist, this)); auto menu = Menu::create(item1, item2, item3, item4, item5, NULL);
menu->setPosition(Vec2(250, visibleSize.height - 200));
menu->alignItemsVerticallyWithPadding(20);
this->addChild(menu); return true;
} //设置和获得分辨率的路径;获取某个文件的路径
void fileUtil::testResolutionDirectories(Ref* sender)
{
//不同的平台的不同的设备它们的分辨率也存在着某些差异
//实例化
auto fileUtil = FileUtils::getInstance();
//清除缓存,清空所有的缓存
fileUtil->purgeCachedEntries(); //默认搜索路径,第一次的默认搜索路径是Resource那个文件夹
std::vector<std::string> _defaultSearchPathArray;
_defaultSearchPathArray = fileUtil->getSearchPaths();
std::vector<std::string> searchPath = _defaultSearchPathArray; //在默认的搜索路径下在添加一个我们自己的搜索路径
searchPath.insert(searchPath.begin(), "Misc");
//设置新的搜索路径为"Misc"
fileUtil->setSearchPaths(searchPath); //获得搜索分辨率资源路径
std::vector<std::string> _defaultResolutionsOrderArray = fileUtil->getSearchResolutionsOrder();
std::vector<std::string> resolutionsOrder = _defaultResolutionsOrderArray; //添加分辨率资源路径
//在依次的在下面的文件名路径下依次的查找所要查找的内容
resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipadhd");
resolutionsOrder.insert(resolutionsOrder.begin() + 1, "resources-ipad");
resolutionsOrder.insert(resolutionsOrder.begin() + 2, "resources-widehd");
resolutionsOrder.insert(resolutionsOrder.begin() + 3, "resources-wide");
resolutionsOrder.insert(resolutionsOrder.begin() + 4, "resources-hd");
resolutionsOrder.insert(resolutionsOrder.begin() + 5, "resources-iphone"); //重新设置路径
fileUtil->setSearchResolutionsOrder(resolutionsOrder); for (int i = 1; i < 7; i++)
{
//创建6个文件名:text~.txt
auto filename = String::createWithFormat("test%d.txt", i);
//fullPathForFilename(filename->getCString())取得当前对象文件的一个绝对路径;如何查找,它会在上面所有设定好的文件名称下,依次的来查找
std::string ret = fileUtil->fullPathForFilename(filename->getCString());
log("%s --> %s", filename->getCString(), ret.c_str());
}
} //搜索路径
void fileUtil::testSearchPath(Ref* sender)
{
//实例化
auto fileUtil = FileUtils::getInstance();
std::string ret;
//清除缓存,清空所有的缓存
fileUtil->purgeCachedEntries();
std::vector<std::string> _defaultSearchPathArray = fileUtil->getSearchPaths();
std::vector<std::string> searchPaths = _defaultSearchPathArray;
//getWritablePath();获得一个可写的路径
std::string writablePath = fileUtil->getWritablePath(); std::string fileName = writablePath + "external.txt";
char szBuf[100] = "Hello Cocos2d-x!";
FILE* fp = fopen(fileName.c_str(), "wb");
if (fp)
{
size_t ret = fwrite(szBuf, 1, strlen(szBuf), fp);
CCASSERT(ret != 0, "fwrite function returned zero value");
fclose(fp);
if (ret != 0)
log("Writing file to writable path succeed");
}
//下面是设置或者添加几个可写分辨路径
searchPaths.insert(searchPaths.begin(), writablePath);
searchPaths.insert(searchPaths.begin() + 1, "Misc/searchpath1");
searchPaths.insert(searchPaths.begin() + 2, "Misc/searchpath2");
fileUtil->setSearchPaths(searchPaths);
//取得分辨路径
std::vector<std::string> _defaultResolutionsOrderArray = fileUtil->getSearchResolutionsOrder();
std::vector<std::string> resolutionsOrder = _defaultResolutionsOrderArray;
//添加一个路径resources-ipad
resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipad");
fileUtil->setSearchResolutionsOrder(resolutionsOrder); for (int i = 1; i<3; i++)
{
auto filename = String::createWithFormat("file%d.txt", i);
ret = fileUtil->fullPathForFilename(filename->getCString());
log("%s --> %s", filename->getCString(), ret.c_str());
} // Gets external.txt from writable path
std::string fullPath = fileUtil->fullPathForFilename("external.txt");
log("external file path = %s", fullPath.c_str());
if (fullPath.length()>0)
{//rb是一个只读的权限
fp = fopen(fullPath.c_str(), "rb");
if (fp)
{
char szReadBuf[100] = { 0 };
int read = fread(szReadBuf, 1, strlen(szBuf), fp);
if (read>0)
{
log("The content of file from writable path: %s", szReadBuf);
}
fclose(fp);
}
}
} //文件查找
//测试文件名查找
void fileUtil::testFilenameLookup(Ref* sender)
{
//实例化
auto sharedFileUtils = FileUtils::getInstance();
ValueMap dict;
dict["grossini.bmp"] = Value("Images/grossini.png");
dict["grossini.xcf"] = Value("Images/grossini.png");
//设置一个按文件名查找的字典
sharedFileUtils->setFilenameLookupDictionary(dict); // Instead of loading carlitos.xcf, it will load grossini.png
auto sprite = Sprite::create("grossini.png");
this->addChild(sprite); auto s = Director::getInstance()->getWinSize();
sprite->setPosition(Vec2(s.width / 2, s.height / 2));
} //判断文件是否存在
//测试文件是否存在
void fileUtil::testIsFileExist(Ref* sender)
{
auto s = Director::getInstance()->getWinSize();
auto sharedFileUtils = FileUtils::getInstance(); Label* pTTF = nullptr;
bool isExist = false; isExist = sharedFileUtils->isFileExist("Images/grossini.png"); pTTF = Label::createWithSystemFont(isExist ? "Images/grossini.png exists" : "Images/grossini.png doesn't exist", "", 20);
pTTF->setPosition(Vec2(s.width / 2, s.height / 3));
this->addChild(pTTF);
} //写plist配置文件
//测试写plist文件
void fileUtil::testWritePlist(Ref* sender)
{
//创建一个字典
auto root = Dictionary::create();
//设置字典的key-》String element value
auto string = String::create("String element value");
root->setObject(string, "string element key");
//创建一个数组
auto array = Array::create();
//在数组里面添加一个字典
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 array"));
arrayInArray->addObject(String::create("string 1 in array"));
array->addObject(arrayInArray); root->setObject(array,"array");
//在字典中在嵌套字典
auto dictInDict = Dictionary::create();
dictInDict->setObject(String::create("string in dictInDict value"), "String in dictInDict key"); //add booleans to the plist
auto booleanObject = Bool::create(true);
dictInDict->setObject(booleanObject, "bool"); //add integer to the plist
auto intObject = Integer::create(624);
dictInDict->setObject(intObject, "integer"); //add float to the plist
auto floatObject = Float::create(524.2);
dictInDict->setObject(floatObject, "float"); //add double to the plist
auto doubleObject = Double::create(524.2);
dictInDict->setObject(doubleObject, "double");
root->setObject(dictInDict, "dictInDict, hello world!"); //end with
//在拿到一个可写的路径getWritablePath();-——》writablePath
std::string writablePath = FileUtils::getInstance()->getWritablePath();
//在拿到的可写路径下添加一个text.plist文件
std::string fullPath = writablePath + "text.plist";
//调用writeToFile方法进行写操作
if (root->writeToFile(fullPath.c_str()))
log("see the plist file at %s", fullPath.c_str());
else
log("write plist file failed"); auto label = LabelTTF::create(fullPath.c_str(), "Arial", 12);
this->addChild(label);
auto winsize = Director::getInstance()->getWinSize();
label->setPosition(Vec2(winsize.width / 2, winsize.height / 3));
//根据文件的内容来创建一个字典
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 doubleValue = (__String*)loadDictInDict->objectForKey("double");
CCLOG("%s", doubleValue->getCString());
auto integerValue = (__String*)loadDictInDict->objectForKey("int");
CCLOG("%s", integerValue->getCString());
}

UserDefault

在上面实现了数据的读写等一些操作,但是游戏的某些数据时要实现持久化的,因此Cocos2d-x引擎中有提供了一个类UserDefault来让我们来实现数据的持久化。UserDefault可以实现数据的存储,但是它不宜储存大量的数据,一般的情况下,用于保存一些游戏设置和玩家偏好设置;数据持久化就是数据能够存储起来,然后在需要的时候可以查找回来,即使设备从新启动也可以查找回来。在UserDefault提供了对int, double, bool和string等数据类型的读写。

UserDefault所支持的数据类型:

在Cocos2d-x中能够多种持久化的方式;

1. 普通文本文件的持久化。

2. UserDefault.可以设置用户的偏好设置等一些少量的数据

3. 属性列表。

4. SQL数据库

API中的常用函数:

 // get value methods
/**根据键值取出布尔值
* Get bool value by key, if the key doesn't exist, will return false.
* You can set the default value, or it is false.
* @param key The key to get value.
* @return Bool value by `key`.
*/
bool getBoolForKey(const char* key);
/**根据键值取出布尔值,如果键不存在,返回defaultValue
* Get bool value by key, if the key doesn't exist, will return passed default value.
* @param key The key to get value.
* @param defaultValue The default value to return if the key doesn't exist.
*/
virtual bool getBoolForKey(const char* key, bool defaultValue);
/**根据键值取出int类型的数据
* Get integer value by key, if the key doesn't exist, will return 0.
* You can set the default value, or it is 0.
* @param key The key to get value.
* @return Integer value of the key.
*/
int getIntegerForKey(const char* key);
/**根据键值取出int类型的数据,如果键不存在,返回defaultValue
* Get bool value by key, if the key doesn't exist, will return passed default value.
* @param key The key to get value.
* @param defaultValue The default value to return if the key doesn't exist.
* @return Integer value of the key.
*/
virtual int getIntegerForKey(const char* key, int defaultValue);
/**根据键值取出float类型的数据
* Get float value by key, if the key doesn't exist, will return 0.0.
* @param key The key to get value.
* @return Float value of the key.
*/
float getFloatForKey(const char* key);
/**根据键值取出float类型的数据,如果键不存在,返回defaultValue
* Get float value by key, if the key doesn't exist, will return passed default value.
* @param key The key to get value.
* @param defaultValue The default value to return if the key doesn't exist.
* @return Float value of the key.
*/
virtual float getFloatForKey(const char* key, float defaultValue);
/**根据键值取出double类型的数据
* Get double value by key, if the key doesn't exist, will return 0.0.
* @param key The key to get value.
* @return Double value of the key.
*/
double getDoubleForKey(const char* key);
/**根据键值取出double类型的数据,如果键不存在,返回defaultValue
* Get double value by key, if the key doesn't exist, will return passed default value.
* @param key The key to get value.
* @param defaultValue The default value to return if the key doesn't exist.
* @return Double value of the key.
*/
virtual double getDoubleForKey(const char* key, double defaultValue);
/**根据键值取出string类型的数据
* Get string value by key, if the key doesn't exist, will return an empty string.
* @param key The key to get value.
* @return String value of the key.
*/
std::string getStringForKey(const char* key);
/**根据键值取出string类型的数据,如果键不存在,返回defaultValue
* Get string value by key, if the key doesn't exist, will return passed default value.
* @param key The key to get value.
* @param defaultValue The default value to return if the key doesn't exist.
* @return String value of the key.
*/
virtual std::string getStringForKey(const char* key, const std::string & defaultValue);
/**根据键值取出Data类型的数据
* Get Data value by key, if the key doesn't exist, will return an empty Data.
* @param key The key to get value.
* @return Data value of the key.
*/
Data getDataForKey(const char* key);
/**根据键值取出Data类型的数据,如果键不存在,返回defaultValue
* Get Data value by key, if the key doesn't exist, will return an empty Data.
* @param key The key to get value.
* @param defaultValue The default value to return if the key doesn't exist.
* @return Data value of the key.
*/
virtual Data getDataForKey(const char* key, const Data& defaultValue);
// set value methods
/**根据键写入布尔值
* Set bool value by key.
* @param key The key to set.
* @param value A bool value to set to the key.
*/
virtual void setBoolForKey(const char* key, bool value);
/**根据键写入int类型数据
* Set integer value by key.
* @param key The key to set.
* @param value A integer value to set to the key.
*/
virtual void setIntegerForKey(const char* key, int value);
/**根据键写入float类型数据
* Set float value by key.
* @param key The key to set.
* @param value A float value to set to the key.
*/
virtual void setFloatForKey(const char* key, float value);
/**根据键写入double类型数据
* Set double value by key.
* @param key The key to set.
* @param value A double value to set to the key.
*/
virtual void setDoubleForKey(const char* key, double value);
/**根据键写入String类型数据
* Set string value by key.
* @param key The key to set.
* @param value A string value to set to the key.
*/
virtual void setStringForKey(const char* key, const std::string & value);
/**根据键写入Data类型数据
* Set Data value by key.
* @param key The key to set.
* @param value A Data value to set to the key.
*/
virtual void setDataForKey(const char* key, const Data& value);
/**调用此函数会将我们所改变的数据保存在.xml文件中去。
* You should invoke this function to save values set by setXXXForKey().
*/
virtual void flush();
/**
* delete any value by key,
* @param key The key to delete value.
*/
virtual void deleteValueForKey(const char* key);
/**
* Returns the singleton.
*/
static UserDefault* getInstance();
/**
*
*/
static void destroyInstance();
/**
* You can inherit from platform dependent implementation of UserDefault, such as UserDefaultAndroid,
* and use this function to set delegate, then UserDefault will invoke delegate's implementation.
* For example, your store native data base or other format store.
* If you don't want to system default implementation after setting delegate, you can just pass nullptr
* to this function.
* @warm It will delete previous delegate
*/
static void setDelegate(UserDefault *delegate);
/** @deprecated Use getInstace() instead.
*/
CC_DEPRECATED_ATTRIBUTE static UserDefault* sharedUserDefault();
/**@deprecated Use destroyInstance() instead.
*/
CC_DEPRECATED_ATTRIBUTE static void purgeSharedUserDefault();
/** All supported platforms other iOS & Android use xml file to save values. This function is return the file path of the xml path.
*/
static const std::string& getXMLFilePath();
/** All supported platforms other iOS & Android and CC_PLATFORM_WINRT use xml file to save values. This function checks whether the xml file exists or not.
* @return True if the xml file exists, false if not.
*/
static bool isXMLFileExist();

实例:

.h files 

#ifndef _USERDEFAULTTEST_SCENE_H_
#define _USERDEFAULTTEST_SCENE_H_
#include "cocos2d.h"
class userDefault : public cocos2d::Layer
{
private:
public:
static cocos2d::Scene* createScene();
virtual bool init();
void testUserDefault(Ref* sendef);
CREATE_FUNC(userDefault);
}; #endif // _USERDEFAULTTEST_SCENE_H_ .cpp files #include "UserDefaultTest.h" USING_NS_CC; Scene* userDefault::createScene()
{
auto scene = Scene::create();
auto layer = userDefault::create();
scene->addChild(layer);
return scene;
} bool userDefault::init()
{
if (!Layer::init())
{
return false;
} Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto item = MenuItemFont::create("Test", CC_CALLBACK_1(userDefault::testUserDefault, this));
auto menu = Menu::create(item, NULL);
this->addChild(menu); return true;
} void userDefault::testUserDefault(Ref* sendef)
{
//set default value
UserDefault::getInstance()->setStringForKey("String", "value1");
UserDefault::getInstance()->setIntegerForKey("Integer", 100);
UserDefault::getInstance()->setFloatForKey("Float", 5.326f);
UserDefault::getInstance()->setDoubleForKey("Double", 3.1415967);
UserDefault::getInstance()->setBoolForKey("Bool", false); //printf value
std::string ret = UserDefault::getInstance()->getStringForKey("String");
CCLOG("string is %s", ret.c_str()); int intValue = UserDefault::getInstance()->getIntegerForKey("Integer");
CCLOG("Integer value is %d", intValue); float floValue = UserDefault::getInstance()->getFloatForKey("Float");
CCLOG("Float value is %f", floValue); double douValue = UserDefault::getInstance()->getDoubleForKey("Double");
CCLOG("Double value is %f", douValue); bool boolValue = UserDefault::getInstance()->getBoolForKey("Bool");
if (boolValue)
CCLOG("bool value is true");
else
CCLOG("bool value is false"); //CCUserDefault::getInstance()->flush();
CCLOG("改变后的数据:");
UserDefault::getInstance()->setStringForKey("String", "value2");
UserDefault::getInstance()->setIntegerForKey("Integer", 10);
UserDefault::getInstance()->setFloatForKey("Float", 15.326f);
UserDefault::getInstance()->setDoubleForKey("Double", 2 * 3.1415967);
UserDefault::getInstance()->setBoolForKey("Bool", true); UserDefault::getInstance()->flush(); //after change value
ret = UserDefault::getInstance()->getStringForKey("String");
CCLOG("string is %s", ret.c_str()); intValue = UserDefault::getInstance()->getIntegerForKey("Integer");
CCLOG("Integer value is %d", intValue); floValue = UserDefault::getInstance()->getFloatForKey("Float");
CCLOG("Float value is %f", floValue); douValue = UserDefault::getInstance()->getDoubleForKey("Double");
CCLOG("Double value is %f", douValue); boolValue = UserDefault::getInstance()->getBoolForKey("Bool");
if (boolValue)
CCLOG("bool value is true");
else
CCLOG("bool value is false");
}

Cocos2d-x之数据的处理的更多相关文章

  1. Pycharm下安装模块

    方法一:使用Pycharm的终端安装 一.网络爬虫 1.安装requests包 作用:简洁且简单的处理HTTP请求的第三方库 网址:https://pypi.org/project/requests/ ...

  2. Cocos2d 利用继承Draw方法制作可显示三维数据(宠物三维等)的三角形显示面板

    很久没有写博客了,这段时间比较忙,又是搬家又是做自己的项目,还有太多琐碎的事情缠身,好不容易抽出时间把最近自己做的一些简单例子记录一下. 在我的项目中,我需要一个显示面板来显示游戏中的一个三维数据,例 ...

  3. cocos2d JS 自定义事件分发器(接收与传递数据) eventManager

    简而言之,它不是由系统自动触发,而是人为的干涉 较多情况用于传递数据 var _listener1 = cc.EventListener.create({ event: cc.EventListene ...

  4. 【cocos2d-x + Lua(2) C++和lua数据通讯之间的互调】

    我们主要解决如下几个问题: 转载注明出处:http://www.cnblogs.com/zisou/p/cocos2dx-lua2.html 1,C++如何获取Lua里面的一个变量值? 2,C++如何 ...

  5. 如何优化cocos2d程序的内存使用和程序大小

    在我完成第一个游戏项目的时候,我深切地意识到"使用cocos2d来制作游戏的开发者们,他们大多会被cocos2d的内存问题所困扰".而我刚开始接触cocos2d的时候,社区里面的人 ...

  6. Cocos2d-x 3.2 学习笔记(十五)保卫萝卜 场景与数据

         保卫萝卜~场景的思路以及数据的存储.      学习要写笔记,记录自己的步骤. 一.场景构建Tiled      关于Tiled网上有一大堆的教程,这个比较好用,特别是构建塔防类的游戏极其简 ...

  7. 如何优化cocos2d程序的内存使用和程序大小:第一部分

    译者: 在我完成第一个游戏项目的时候,我深切地意识到“使用cocos2d来制作游戏的开发者们,他们大多会被cocos2d的内存问题所困扰”.而我刚开始接触cocos2d的时候,社区里面的人们讨论了一个 ...

  8. 在cocos2d里面如何使用Texture Packer和像素格式来优化spritesheet

    免责申明(必读!):本博客提供的所有教程的翻译原稿均来自于互联网,仅供学习交流之用,切勿进行商业传播.同时,转载时不要移除本申明.如产生任何纠纷,均与本博客所有人.发表该翻译稿之人无任何关系.谢谢合作 ...

  9. cocos基础教程(5)数据结构介绍之cocos2d::Value

    1.概述 cocos2d::Valie 是一个包含了很多原生类型(int,float,double,bool,unsigned char,char* 和 std::string)外加 std::vec ...

  10. cocos2d::Vector

    C++中的vector使用范例 一.概述 vector是C++标准模板库中的部分内容,它是一个多功能的,能够操作多种数据结构和算法的模板类和函数库.vector是一个容器,它能够存放各种类型的对象,简 ...

随机推荐

  1. BFS+打印路径

    题目是给你起点sx,和终点gx:牛在起点可以进行下面两个操作: 步行:John花一分钟由任意点X移动到点X-1或点X+1. 瞬移:John花一分钟由任意点X移动到点2*X. 你要输出最短步数及打印路径 ...

  2. linux php 中session 多站点共享session问题

    linux php 中session默认file 假如修改为redis php.ini session.save_handler = "files"; session.save_p ...

  3. AJAX —— JSON 字符串 与 JSON 对象

    一.JSON 字符串转 JSON 对象 ----> JSON.parse(JString); 1 // JSON 字符串转 JSON 对象 ----> JSON.parse(JString ...

  4. elasticsearch 基础 —— 索引、更新文档

    索引文档 通过使用 index API ,文档可以被 索引 -- 存储和使文档可被搜索 . 但是首先,我们要确定文档的位置.正如我们刚刚讨论的,一个文档的 _index . _type 和 _id 唯 ...

  5. iOS crash log 解析

    iOS开发中,经常遇到App在开发及测试时不会有问题,但是装在别人的设备中会出现各种不定时的莫名的 crash,因为iOS设备会保存应用的大部分的 crash Log,所以可以通过 crash Log ...

  6. Codeforces 1208F Bits And Pieces 位运算 + 贪心 + dp

    题意:给你一个序列a, 问a[i] ^ (a[j] & a[k])的最大值,其中i < j < k. 思路:我们考虑对于每个a[i]求出它的最优解.因为是异或运算,所以我们从高位向 ...

  7. 九、Rxjs请求对Observable进行封装

    1.引入 Http.Jsonp.Rxjs 三个模块 2.请求中添加一个 .map(res => res.json) 问题 1.Property 'map' does not exist on t ...

  8. setenv和dos2unix碰到的问题

    两个比较傻的小问题 setenv  ethaddr 00:0a:35:00:01:26 提示只能修改一次,束手无策,难道要改uboot吗 同事提示加上-f setenv -f ethaddr 00:0 ...

  9. AbstractQueuedSynchronizer简单使用

    AQS是JUC中很多同步组件的构建基础,简单来讲,它内部实现主要是状态变量state和一个FIFO队列来完成,同步队列的头结点是当前获取到同步状态的结点,获取同步状态state失败的线程,会被构造成一 ...

  10. mongdb 基本命令

    1 数据库常用命令 1.Help查看命令提示 help db.help(); db.yourColl.help(); db.youColl.find().help(); rs.help(); 2.切换 ...