cocos2dx CCArray类

前端之家收集整理的这篇文章主要介绍了cocos2dx CCArray类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、继承自CCObject

class CC_DLL CCArray : public CCObject


2、如果通过create创建,会加入自动释放池,通过new创建则不会,所以使用时要记得retain,然后释放时
使用release。
CCArray* CCArray::create()
{
    CCArray* pArray = new CCArray();

    if (pArray && pArray->init())
    {
        pArray->autorelease();
    }
    else
    {
        CC_SAFE_DELETE(pArray);
    }
    
    return pArray;
}
3、addObject 增加一个,会调用retain

void CCArray::addObject(CCObject* object)
{
    ccArrayAppendObjectWithResize(data,object);
}

--》
/** Appends an object. Capacity of arr is increased if needed. */
void ccArrayAppendObjectWithResize(ccArray *arr,CCObject* object)
{
	ccArrayEnsureExtraCapacity(arr,1);
	ccArrayAppendObject(arr,object);
}

--》ccArrayAppendObject
/** Appends an object. Behavior undefined if array doesn't have enough capacity. */
void ccArrayAppendObject(ccArray *arr,CCObject* object)
{
    CCAssert(object != NULL,"Invalid parameter!");
    object->retain(); //retain对象
	arr->arr[arr->num] = object;
	arr->num++;
}

4、 移除其中一个,默认会release

/** Remove a certain object */
void removeObject(CCObject* object,bool bReleaSEObj = true);

//实现:
void CCArray::removeObject(CCObject* object,bool bReleaSEObj/* = true*/)
{
    ccArrayRemoveObject(data,object,bReleaSEObj);
}

-->>
/** Searches for the first occurrence of object and removes it. If object is not
 found the function has no effect. */
void ccArrayRemoveObject(ccArray *arr,CCObject* object,bool bReleaSEObj/* = true*/)
{
	unsigned int index = ccArrayGetIndexOfObject(arr,object);
	if (index != CC_INVALID_INDEX)
    {
		ccArrayRemoveObjectAtIndex(arr,index,bReleaSEObj);
    }
}

-->>ccArrayRemoveObjectAtIndex
/** Removes object at specified index and pushes back all subsequent objects.
 Behavior undefined if index outside [0,num-1]. */
void ccArrayRemoveObjectAtIndex(ccArray *arr,unsigned int index,bool bReleaSEObj/* = true*/)
{
    CCAssert(arr && arr->num > 0 && index < arr->num,"Invalid index. Out of bounds");
    if (bReleaSEObj)
    {
        CC_SAFE_RELEASE(arr->arr[index]); //release
    }
    
	arr->num--;
	
	unsigned int remaining = arr->num - index;
	if(remaining>0)
    {
		memmove((void *)&arr->arr[index],(void *)&arr->arr[index+1],remaining * sizeof(CCObject*));
    }
}

5、移除全部,都会release

void CCArray::removeAllObjects()
{
    ccArrayRemoveAllObjects(data);
}

-->>
/** Removes all objects from arr */
void ccArrayRemoveAllObjects(ccArray *arr)
{
	while( arr->num > 0 )
    {
		(arr->arr[--arr->num])->release();
    }
}
6、析构

CCArray::~CCArray()
{
    ccArrayFree(data);
}

-->>
/** Frees array after removing all remaining objects. Silently ignores NULL arr. */
void ccArrayFree(ccArray*& arr)
{
    if( arr == NULL ) 
    {
        return;
    }
	ccArrayRemoveAllObjects(arr);
	
	free(arr->arr);
	free(arr);

    arr = NULL;
}

猜你在找的Cocos2d-x相关文章