Cocos2D X:如何检查plist文件是否存在密钥

Cocos2D X: How to check if a key exists for a plist file?

本文关键字:plist 文件 是否 密钥 存在 检查 何检查 Cocos2D      更新时间:2023-10-16

我正在使用以下代码从我的游戏的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
    }