数组与字符串三(Cocos2d-x 3.x _Array容器)
"程序=數(shù)據(jù)結(jié)構(gòu)+算法"
在面向?qū)ο蟮恼Z言中,諸如數(shù)組、堆棧、隊列等的結(jié)構(gòu)都被封裝成了特定的類,按照特定數(shù)據(jù)結(jié)構(gòu)的算法設(shè)計起來,這就是容器類。
Cocos2d-x中,能使用的容器類:C++標準容器類、Cocos2d-x中定義的容器類。其中,列表容器類包括:_Array、Vector<T>和ValueVector;字典容器包括:_Dictionary、Map<K,V>、ValueMap和ValueMapIntKey。
_Array 繼承于Ref類,(2.x版本中是CCArray),通過引用計數(shù)管理內(nèi)存。容納的是Ref及子類所創(chuàng)建的對象指針。
實現(xiàn): 點擊按鈕,響應(yīng)事件為創(chuàng)建100個精靈。
主要實現(xiàn)代碼:
1、在Helloworld.h文件中聲明
#define MAX_COUNT 100??
即,所用到的_Array容器創(chuàng)建的成員變量的起始容量的值
2、在Helloworld.cpp文件中,
//增加菜單項 點擊之后出現(xiàn)精靈
?auto goItem = MenuItemImage::create(
??"go-down.png",
??"go-up.png",
??CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
?//設(shè)置菜單圖片的位置
?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);
?//創(chuàng)建 _Array* 類型的變量list,參數(shù)為它的初始容量
?this->list? = __Array::createWithCapacity(MAX_COUNT);
?//list的創(chuàng)建是通過靜態(tài)方法創(chuàng)建,如果不調(diào)用retain函數(shù),當init函數(shù)結(jié)束時,會自動釋放,當別的函數(shù)中再使用list時,就會報錯
?this->list->retain();
?//所要創(chuàng)建精靈的個數(shù)
?for(int i = 0;i < MAX_COUNT; ++i){
??Sprite* sprite = Sprite::create("Ball.png");
??this->list->addObject(sprite);
//觸摸菜單圖標后觸發(fā)的函數(shù)
void HelloWorld::menuCloseCallback(Ref* pSender)
{
?Ref* obj = nullptr;
?log("list->count() = %d",this->list->count());
?Size visibleSize = Director::getInstance()->getVisibleSize();
?//循環(huán)遍歷 容器中的數(shù)據(jù)
?CCARRAY_FOREACH(this->list, obj) {
?//獲得精靈對象?
??Sprite* sprite = (Sprite*)obj;
??//隨機生成精靈的x、y坐標
??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);
?}
}
HelloWorld::~HelloWorld()
{
?//前面說過手動設(shè)置保持list的內(nèi)存,現(xiàn)在要手動釋放
?//釋放list里面的所有對象
?this->list->removeAllObjects();
?//釋放list容器對象
?CC_SAFE_RELEASE_NULL(this->list);
}
結(jié)果:
?
轉(zhuǎn)載于:https://www.cnblogs.com/revenge/p/6089302.html
總結(jié)
以上是生活随笔為你收集整理的数组与字符串三(Cocos2d-x 3.x _Array容器)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sm4加密 解密(oc)
- 下一篇: UVALive 4035 - Undet