Introduction to the _ Dictionary container and instance in the Cocos2d-x

Source: Internet
Author: User

Introduction to the _ Dictionary container and instance in the Cocos2d-x
In the era of Cocos2d-x 2. x, The _ Dictionary class is a CCDictionary class designed to mimic the NSDictionary class in Objective-C and manage memory by referencing the count. _ Dictionary is inherited from the Ref class, so it can accommodate the Ref class and the Object Pointer created by the subclass.

1. Create a _ Dictionary object

There are many functions to create a _ Dictionary object. The following is a summary of common functions:

Static _ Dictionary * create (). Create _ Dictionary.

Static _ Dictionary * createWithDictionary (_ Dictionary * srcDict ). Use an existing _ Dictionary to create a new _ Dictionary.

Static _ Dictionary * createWithContentsOfFile (const char * pFileName ). Create _ Dictionary from the property list file.

2. Add Elements

The elements added to the _ Dictionary object must be "key-value" pairs. The "key" can be a string (std: string) type or an integer (signed int) type, the "value" must be the object pointer type of the Ref and its subclass. Below is a summary of common functions:

Void setObject (Ref * pObject, const std: string & key ). Insert a key-value pair, where pObject is a value and key is a key ". If this is the first call, the "key" type of __dictionary is string type, and then the integer "key" cannot be inserted ". If the key already exists, the old key-value pair is released and removed, and replaced by a new one.

Void setObject (Ref * pObject, intptr_t key ). Insert a "key-value" pair, where pObject is "value", key is "key", intptr_t is an alias of the signed int type, and integer type. If this is the first call, the "key" type of __dictionary is an integer type, then the string "key" cannot be inserted. If the "key" already exists ", the old "key-value" pair is released and removed, and replaced by a new one.

3. Remove Elements

The following is a summary of commonly used functions for removing elements from the _ Dictionary container:

Void removeObjectForKey (const std: string & key ). Removes an element by specifying a key.

Void removeObjectForKey (intptr_t key ). Removes an element by specifying a key.

Void removeObjectsForKeys (_ Array * pKeyArray ). Removes an element from a set of _ arrays.

Void removeObjectForElememt (DictElement * pElement ). Remove an element by specifying it.

Void removeAllObjects (). Remove all elements.

4. Search for elements

We can also use the following function to find the elements in the _ Dictionary container:

Ref * objectForKey (const std: string & key ). Returns the "value" of the specified string type "key ".

Ref * objectForKey (intptr_t key ). Returns the "value" of the specified integer "key ".

Const _ String * valueForKey (const std: string & key ). Returns the "value" of the specified String type "key". The returned value is the _ String pointer type. Here we assume that the "value" is the _ String pointer type. If it is not or is not found, returns an empty string.

Const _ String * valueForKey (intptr_t key ). Return the "value" of the specified integer "key". The returned value is of the _ String pointer type. Here, we assume that the "value" is a _ String pointer. If it is not or is not found, an empty String is returned.

5. Other operation functions

In addition, there are many operate_dictionary object functions. Below is a summary of common functions:

_ Array * allKeys (). Returns a _ Array container containing the "value" of all "keys.

Unsigned int count (). Returns the number of elements.

Bool writeToFile (const char * fullPath ). Write _ Dictionary to an attribute list file. The written "value" must be string type.

6. traverse the _ Dictionary container

The Cocos2d-x provides two macros for the traversal _ Dictionary container:

CCDICT_FOREACH. Traverse the _ Dictionary container.

Instance :__ Dictionary container

Next we will introduce the functions in the _ Dictionary container through an example. Scenario: Click Go in the lower-right corner to add 100 Ball and 100 icon genie to the scenario.

_ Dictionary container instance

To learn how to use the _ Dictionary class, we create 100 Ball Genie and 100 icon genie in the program, and add them to different _ Dictionary containers.

Let's take a look at the code section. The HelloWorldScene. h code is as follows:

#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #define MAX_COUNT 100① class HelloWorld : public cocos2d::Layer{cocos2d::__Dictionary* dict1; ②cocos2d::__Dictionary* dict2; ③ public: ~HelloWorld();④    static cocos2d::Scene* createScene();    virtual bool init();          void menuCloseCallback(cocos2d::Ref* pSender);        CREATE_FUNC(HelloWorld);}; #endif // __HELLOWORLD_SCENE_H__

Line 1 of the above Code # define MAX_COUNT 100 defines the macro MAX_COUNT, which defines the number of genie generated at a time. The member variables dict1 and dict2. Line 4 of the Code declares the destructor. We need to release the member variables dict1 and dict2 In the destructor.

The init function code in HelloWorldScene. cpp is as follows:

bool HelloWorld::init(){if ( !Layer::init() ){return false;} Size visibleSize = Director::getInstance()->getVisibleSize();Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto goItem = MenuItemImage::create("go-down.png","go-up.png",CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); goItem->setPosition(Vec2(origin.x + visibleSize.width - goItem->getContentSize().width/2 ,origin.y + goItem->getContentSize().height/2)); auto menu = Menu::create(goItem, NULL);menu->setPosition(Vec2::ZERO);this->addChild(menu, 1); this->dict1  = __Dictionary::create();①this->dict1->retain();②this->dict2  = __Dictionary::create();this->dict2->retain(); for(int i = 0;i < MAX_COUNT; ++i){ ③ auto sprite1 = Sprite::create("Ball.png");④this->dict1->setObject(sprite1, i);⑤ auto sprite2 = Sprite::create("icon.png");⑥__String *key = __String::createWithFormat("key%d",i);⑦this->dict2->setObject(sprite2, key->getCString());⑧}return true;}

Init is a function used to initialize the scenario. In this function, we create 200 Genie and place them in the _ Dictionary * type dict1 and dict2 member variables respectively. The Code in line ① is to create a dict1 member variable of the _ Dictionary * type and use the create FUNCTION. Line ② code this-> dict1-> retain () is very important. retain is to ensure that the memory of the dict1 object is not automatically released after a game loop event, which involves the Ref memory management issue, we will give you a detailed introduction in Chapter 19th. If this-> dict1-> retain () statement is used, the dict1 object is released and an error occurs in the dict1 container object of other functions.

Line ③ code is used to create a Sprite object cyclically. Line 4 of Code creates a Ball sprite object. Line 5 of code this-> dict1-> setObject (sprite1, I) uses the cyclic variable I as the key, add the Ball genie object to the dict1 container object. Line 6 of code is to create an icon sprite object. The Code in line 7 creates a string based on the cyclic variable I, such as key0 and key1. The code in the nth line adds the icon sprite object to the dict2 container object.

Note that these genie objects are not added to the scene, so they do not appear when the scene is displayed.

The menuCloseCallback function code in HelloWorldScene. cpp is as follows:

void HelloWorld::menuCloseCallback(Ref* pSender){ Size visibleSize = Director::getInstance()->getVisibleSize(); DictElement* pElement; ① log("Dict1 key-value count = %d",this->dict1->count());CCDICT_FOREACH(dict1, pElement)  ②{int key = pElement->getIntKey();  ③log("Add Sprite %d", key); Sprite* sprite = (Sprite*)pElement->getObject();④ int x = CCRANDOM_0_1() * visibleSize.width;int y = CCRANDOM_0_1() * visibleSize.height; sprite->setPosition( Vec2(x, y) );this->removeChild(sprite);this->addChild(sprite);}  log("Dict2 key-value count = %d",this->dict2->count());CCDICT_FOREACH(dict2, pElement)  ⑤{const char *key = pElement->getStrKey();  ⑥log("Add Sprite %s", key); Sprite* sprite = (Sprite*)pElement->getObject(); int x = CCRANDOM_0_1() * visibleSize.width;int y = CCRANDOM_0_1() * visibleSize.height; sprite->setPosition( Vec2(x, y) );this->removeChild(sprite);this->addChild(sprite);} }

This function is called after the player touches the Go button. The first line of code DictElement * pElement is the _ Dictionary element (DictElement) pointer, which will be used in loop traversal. The main functions of the DictElement class are as follows:

Const char * getStrKey (). Obtains the string key of an element.

Intptr_t getIntKey (). Obtains the integer key of an element.

Ref * getObject (). Obtain the value in the element.

Line ② code CCDICT_FOREACH (dict1, pElement) traverses the _ Dictionary container using the CCDICT_FOREACH macro. The first parameter of the macro, dict1, is the _ Dictionary object pointer, the second pElement is the _ Dictionary element (DictElement) pointer previously declared. Line ③ code int key = pElement-> getIntKey () to obtain the integer key of the element. The fourth line of code Sprite * sprite = (Sprite *) pElement-> getObject () gets the value in the element.

Line ⑤ code CCDICT_FOREACH (dict2, pElement) is used to traverse the dict2 object. Different from dict1, dict2 uses the string type as the key. The key can be obtained through the Code const char * key = pElement-> getStrKey () In line 6.

The Destructor code in HelloWorldScene. cpp is as follows:

HelloWorld::~HelloWorld(){this->dict1->removeAllObjects();CC_SAFE_RELEASE_NULL(this->dict1); this->dict2->removeAllObjects();CC_SAFE_RELEASE_NULL(this->dict2);}

To release some resources in the destructor, you must first remove all elements in the container and then release the container object through the CC_SAFE_RELEASE_NULL macro.

More content please pay attention to the first domestic Cocos2d-x 3.2 version of the book "Cocos2d-x practice: C ++ volume" book exchange discussion site: http://www.cOcoagame.net
For more exciting video courses, please follow the Cocos course in Zhijie class: http: // v.51wOrk6.com
Welcome to the Cocos2d-x Technology Discussion Group: 257760386 welcome to the knowledge of the iOS classroom public platform


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.