Cocos2D X:如何检查plist文件是否存在密钥
Cocos2D X: How to check if a key exists for a plist file?
我正在使用以下代码从我的游戏的plist读取数据:
int levelNum = SOME_VALUE_FROM_OUTSIDE;
ValueMap mapFile = FileUtils::getInstance()->getValueMapFromFile("LevelDetails.plist");
std::string strLevel = std::to_string(levelNum);
ValueMap mapLevel = mapFile.at(strLevel).asValueMap();
LevelDetails.list是一个以dictionary为根的plist。问题是,有时可能没有名为levelNum/strLevel的键。因此,在运行以下行之前,我必须检查密钥是否存在:
ValueMap mapLevel = mapFile.at(strLevel).asValueMap(); //Throws exception occasionally
那么,检查名为levelNum/strLevel的键是否存在的正确方法是什么呢?
因为ValueMap是std::unordered_map,所以可以使用该类中的方法:
if (mapFile.count(strLevel).count() > 0) {
ValueMap mapLevel = mapFile.at(strLevel).asValueMap();
}
在cocos2d-x中的ValueMap声明是:
typedef std::unordered_map<std::string, Value> ValueMap;
您还可以使用find
方法,该方法将向键元素对返回迭代器,或者如果找不到键,则返回过期迭代器。
auto it = mapFile.find(strLevel);
if (it != mapFile.end()) {
it->first; //key
it->second; //element
}
else {
//key not found
}
我遇到这个问题也是出于类似的原因,我认为我已经找到了一个合适的解决方案,使用cocos2d-x3.11.1(也应该适用于旧版本)。
if( mapFile.at(strLevel).getType() != Value::Type::NONE ){
//OR if( mapFile[strLevel].getType() != Value::Type::NONE ) {
//if reached here then the 'key exists', thus perform desired line.
ValueMap mapLevel = mapFile.at(strLevel).asValueMap();
}
您也可以对照"CCValue.h"中定义的特定类型进行检查,例如:
Value::Type::MAP
我们使用的是:
string fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename("file.plist");
auto dataFromPlist = cocos2d::FileUtils::getInstance()->getValueMapFromFile(fullPath);
if (!dataFromPlist["key1"].isNull())
{
auto map = dataFromPlist["key1"].asValueMap();
//Do something else
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 通过Cocos2dx中的plist文件加载动画
- Cocos2D X:如何检查plist文件是否存在密钥
- 无法使用XCode从命令行目标读取plist文件