Search code examples
iphoneioscocos2d-iphoneplistcocos2d-x

cocos2d-x how to read plist into an array


i want to read a plist using cocos2d-x (c++) here is my 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>

it's basically an array of dictionary that consist of (x, y) coordinates. my original code for reading is:

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

but Now i need to translate it into cocos2d-x in c++. i've googled some article but they are all about reading plist into dictionary. i need an array.

EDIT:::

Now i've changed my plist format:

<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>

what should i do??? I still get the same error:

CCDictionary<std::string, CCObject*>* dict = CCFileUtils::dictionaryWithContentsOfFile(plistPath);
int x = (int)dict->objectForKey("11x");
int y = (int)dict->objectForKey("11y");

won't work. Please try it out first. see if you can read a int from the sample plist


Solution

  • Try the follwing line of code

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

    EDIT

    or you can try this too...

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

    EDIT-2

    Try Following code in case of root is Dictionary

       var1 = atoi(valueForKey("blendFuncSource", dictionary));
        var2 = atoi(valueForKey("blendFuncDestination", dictionary));
    

    Look Inside CCParticleSystem.cpp class you might get batter idea. check bool CCParticleSystem::initWithDictionary(CCDictionary<std::string, CCObject*> *dictionary) inside CCParticleSystem.cpp class

    Regards, Nikhil