簡體   English   中英

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.plist是一個以字典為根的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-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

我們使用的是:

    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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM