cocos2d-x移植于cocos2d-iphone,cocos2d-iphone的架构和设计更符合Objective-C的语法,所以cocos2d-x在移植的过程中,也引入了CCArray的概念!
CCArray在设计和使用上更符合Objective-C的风格,类似于Objective-C中的NSArray!
1. CCArray只是提供了一个面向对象的封装类
其继承于CCObject类(CCObject的存在主要是为了自动管理内存),并提供了一系列接口,包括
创建
- <span style="font-size:14px;"> /** Create an array */
- static CCArray* create();
- /** Create an array with some objects */
- static CCArray* create(CCObject* pObject, ...);
- /** Create an array with one object */
- static CCArray* createWithObject(CCObject* pObject);
- /** Create an array with capacity */
- static CCArray* createWithCapacity(unsigned int capacity);
- /** Create an array with an existing array */
- static CCArray* createWithArray(CCArray* otherArray);</span>
添加
- <span style="font-size:14px;">/** Add a certain object */
- void addObject(CCObject* object);
- /** Add all elements of an existing array */
- void addObjectsFromArray(CCArray* otherArray);
- /** Insert a certain object at a certain index */
- void insertObject(CCObject* object, unsigned int index);</span>
删除
- <span style="font-size:14px;">/** Remove last object */
- void removeLastObject(bool bReleaseObj = true);
- /** Remove a certain object */
- void removeObject(CCObject* object, bool bReleaseObj = true);
- /** Remove an element with a certain index */
- void removeObjectAtIndex(unsigned int index, bool bReleaseObj = true);
- /** Remove all elements */
- void removeObjectsInArray(CCArray* otherArray);
- /** Remove all objects */
- void removeAllObjects();
- /** Fast way to remove a certain object */
- void fastRemoveObject(CCObject* object);
- /** Fast way to remove an element with a certain index */
- void fastRemoveObjectAtIndex(unsigned int index);</span>
其中比较有意思的是remove和fastRemove方法,看了源码可知
remove是比较完整的从CCArray对象中删除
而fastRemove只是将对应的CCArray中的某个元素进行了释放
从代码来看,区别主要在于有没有讲删除元素之后的元素向前移动覆盖掉删除元素的位置,差别代码如下:
- <span style="font-size:14px;">unsigned int remaining = arr->num - index;
- if(remaining>0)
- {
- memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(CCObject*));
- }</span>
2. 细节是用c来实现的,其数据结构为
- <span style="font-size:14px;">typedef struct _ccArray {
- unsigned int num, max;
- CCObject** arr;
- } ccArray;</span>
就是这么简单,一个指向CCObject指针的指针(也可以认为是一个数组元素为CCObject指针的数组),一个最大容量和当前元素数量!
这里使用CCObject指针作为元素类型,是为了达到自动管理内存的目的
以及对应CCArray类的接口的一些实现,具体参看代码ccArray.h和ccArray.cpp(注意大小写。。。)
3. 另一个ccArray
在ccArray.h的下半段,还有一个结构体的定义
- <span style="font-size:14px;">typedef struct _ccCArray {
- unsigned int num, max;
- void** arr;
- } ccCArray;</span>
为什么会有ccCArray的存在?难道ccArray不够吗?
确实是不够,因为ccArray的数组元素类型是CCObject*,但是我们的项目甚至包括引擎中的类型,不一定都是CCObject的子类,ccCArray是为我们提供了一套近似于ccArray的接口,存储类型更为宽泛
4. 使用CCArray注意事项
CCArray一般不会被添加到其他的类中,所以其引用计数为1,并且被设置为autorelease
所以,创建的CCArray对象一定要retain,并在其析构方法中调用release释放内存