智慧 + 毅力 = 无所不能

正确性、健壮性、可靠性、效率、易用性、可读性、可复用性、兼容性、可移植性...

导航

cocos2d-x CCArray

Posted on 2013-07-17 17:01  Bill Yuan  阅读(566)  评论(0编辑  收藏  举报

转自:http://blog.csdn.net/onerain88/article/details/8164210

1. CCArray只是提供了一个面向对象的封装类

其继承于CCObject类(CCObject的存在主要是为了自动管理内存),并提供了一系列接口,包括

创建

/** 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);

添加

/** 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);

删除

/** 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);

等等。。。

 

其中比较有意思的是remove和fastRemove方法,看了源码可知

remove是比较完整的从CCArray对象中删除

而fastRemove只是将对应的CCArray中的某个元素进行了释放

从代码来看,区别主要在于有没有讲删除元素之后的元素向前移动覆盖掉删除元素的位置,差别代码如下:

unsigned int remaining = arr->num - index;  
if(remaining>0)  
{  
    memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(CCObject*));  
}

2. 细节是用c来实现的,其数据结构为

typedef struct _ccArray {  
    unsigned int num, max;  
    CCObject** arr;  
} ccArray;

就是这么简单,一个指向CCObject指针的指针(也可以认为是一个数组元素为CCObject指针的数组),一个最大容量和当前元素数量!

 

这里使用CCObject指针作为元素类型,是为了达到自动管理内存的目的

以及对应CCArray类的接口的一些实现,具体参看代码ccArray.h和ccArray.cpp(注意大小写。。。)

3. 另一个ccArray

在ccArray.h的下半段,还有一个结构体的定义

typedef struct _ccCArray {  
    unsigned int num, max;  
    void** arr;  
} ccCArray;

乍一看和ccArray差不多,其实其主要差别是数组元素类型 void*

 

为什么会有ccCArray的存在?难道ccArray不够吗?

确实是不够,因为ccArray的数组元素类型是CCObject*,但是我们的项目甚至包括引擎中的类型,不一定都是CCObject的子类,ccCArray是为我们提供了一套近似于ccArray的接口,存储类型更为宽泛

 

4. 使用CCArray注意事项

CCArray一般不会被添加到其他的类中,所以其引用计数为1,并且被设置为autorelease

所以,创建的CCArray对象一定要retain,并在其析构方法中调用release释放内存