如何从plist文件中读取数组?

我想用cocos2d-x读取一个plist文件,如下所示:

<array> <dict> <key>x</key> <integer>0</integer> <key>y</key> <integer>0</integer> </dict> <dict> <key>x</key> <integer>140</integer> <key>y</key> <integer>12</integer> </dict> <dict> <key>x</key> <integer>120</integer> <key>y</key> <integer>280</integer> </dict> <dict> <key>x</key> <integer>40</integer> <key>y</key> <integer>364</integer> </dict>
<array>

它是由x, y形式的坐标组成的基础数组序列,我使用的初始代码如下:

NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"w%i", world] ofType:@"plist"];
NSMutableArray* points = [NSMutableArray arrayWithContentsOfFile:path];

但是现在,我需要将上述代码翻译成用C++编写的cocos2d-x中,虽然用google搜索了一些文章,但是它们却无法解决我的问题,有没有人可以提供给我一个可利用的数组?
注:
现在,我更改了plist文件的格式:

<dict> <key>11x</key> <integer>0</integer> <key>11y</key> <integer>0</integer> <key>12x</key> <integer>140</integer> <key>12y</key> <integer>12</integer>
<dict>

但仍然出现一样的错误:

CCDictionary<std::string, CCObject*>* dict = CCFileUtils::dictionaryWithContentsOfFileplistPath;
int x = intdict->objectForKey"11x";
int y = intdict->objectForKey"11y";

我该如何解决?

原问题:cocos2d-x how to read plist into an array

答:NIKHIL
你可以尝试如下代码:

//const char *pszPath = CCFileUtils::fullPathFromRelativePathplistName;
//consider that file is in resource bundle..
// CCDictionary<std::string, CCObject*> *plistDictionary=CCFileUtils::dictionaryWithContentsOfFile"testplist.plist";
// CCArray *testitems = CCArray*plistDictionary->objectForKey"root";

或者你也可以这样操作:

CCDictionary<std::string, CCObject*> *plistDictionary = CCFileUtils::dictionaryWithContentsOfFile"testplist.plist"; CCMutableArray<CCObject*> *testitems = CCMutableArray<CCObject*>*plistDictionary->objectForKey"root"; CCLog"COUNT: %d", testitems->count;

答:Inder Kumar Rathore
我不太清楚如何如何读取数组,所以,你可以先按如下方法更改plist文件:

<dict> <key>root</key> <array> <dict> <key>x</key> <integer>0</integer> <key>y</key> <integer>0</integer> </dict> <dict> <key>x</key> <integer>140</integer> <key>y</key> <integer>12</integer> </dict> <dict> <key>x</key> <integer>120</integer> <key>y</key> <integer>280</integer> </dict> <dict> <key>x</key> <integer>40</integer> <key>y</key> <integer>364</integer> </dict> <array>
</dict>

然后:

CCDictionary<std::string, CCObject*> *dict = CCFileUtils::dictionaryWithContentsOfFile"yourFile.plist";
CCArray *testitems = CCArray*dict->objectForKey"root";

答:m.ding
当你读取dictionary对象中的项目并使用ObjectForKey”BLA”命令时,你可以按照下述方法将它转换为CCString*:

CCString* tmpStr = CCString*yourDict->ObjectForKey"KEY"; int x = tmpStr->toInt;

发表评论

电子邮件地址不会被公开。 必填项已用*标注