cocos2d-x的CCArray是数据结构类,对游戏存储数组型数据做了优化。它模拟了苹果NSMutableArray的功能,但是执行效率更高。
(1)创建
//创建一个数组array static CCArray* create(); //使用一些对象创建数组 static CCArray* create(CCObject* pObject,...); //使用一个对象创建数组 static CCArray* createWithObject(CCObject* pObject); //创建一个指定大小的数组 static CCArray* createWithCapacity(unsigned int capacity); //使用一个现有的CCArray数组来新建一个数组 static CCArray* createWithArray(CCArray* otherArray);
//插入一个对象 void addObject(CCObject* object); //插入一个已经存在的数组的全部对象 void addObjectFromArray(CCArray* otherArray); //在一个确定的索引位置插入一个对象 void insertObject(CCObject* object,unsigned int index);
//移除最后的一个对象 void removeLastObject(bool bReleaseObj=true); //移除一个确定的对象 void removeObject(CCObject* object, bool bReleaseObj=true); //移除一个确定索引位置的元素 void removeObjectAtIndex(unsigned int index, bool bReleaseObj=true); //移除数组中的全部元素 void removeObjectsInArray(CCArray* otherArray); //移除所有对象 void removeAllObjects(); //快速移除一个对象 void fastRemoveObject(CCObject* object); //快速移除一个确定索引位置的对象 void fastRemoveObjectAtIndex(unsigned int index);
两者的区别,就在于删除元素之后,是否把数组之后的元素向前移动覆盖掉之前位置的元素。remove是从CCArray中完全的移除,fastRemove只是将CCArray中对应的对象释放掉了,没改变整个CCArray结构。所以remove后,数组有向前覆盖;fastRemove后,数组没有向前覆盖。
CCArray一般不会被add到其他类中,所以它的引用计数是1,并且设置为autorelease对象。创建CCArray对象并且retain,然后在这个类中的析构函数中调用release方法来释放内存。如果CCObject对象添加到CCArray中,那么CCObject对象的引用计数将会加1.