【问题标题】:Cocos2D X: How to check if a key exists for a plist file?Cocos2D X:如何检查 plist 文件的密钥是否存在?
【发布时间】:2014-10-17 11:33:56
【问题描述】:

我正在使用以下代码从 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.plist 是一个以字典为根的 plist。问题是有时可能没有名为 levelNum / strLevel 的键。所以我必须在运行此行之前检查密钥是否存在:

ValueMap mapLevel = mapFile.at(strLevel).asValueMap(); //Throws exception occasionally

那么检查名为 levelNum / strLevel 的键是否存在的正确方法是什么?

【问题讨论】:

    标签: c++ ios cocos2d-x cocos2d-x-3.0


    【解决方案1】:

    因为 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;
    

    【讨论】:

      【解决方案2】:

      您还可以使用find 方法,如果未找到该键,该方法将返回一个迭代器到键元素对或一个过去的迭代器。

      auto it = mapFile.find(strLevel);
      
      if (it != mapFile.end()) {
          it->first; //key
          it->second; //element
      }
      else {
          //key not found
      }
      

      【讨论】:

        【解决方案3】:

        我出于类似的原因遇到了这个问题,并认为我找到了一个合适的解决方案,使用 cocos2d-x-3.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
        

        【讨论】:

          【解决方案4】:

          我们使用的是这样的:

              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
              }
          

          【讨论】:

            猜你喜欢
            • 2022-01-11
            • 2012-05-11
            • 2013-07-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多