[2]Cocos2d-x之引用计算(referenceCount)的增减时机

前端之家收集整理的这篇文章主要介绍了[2]Cocos2d-x之引用计算(referenceCount)的增减时机前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
总结:
1、当节点( 节点指像Scene、Layer、Sprite等继承Node的子类)被创建时,引用计数( referenceCount)加1。
2、当节点添加到父节点或 执行动作时,没错执行动作也会加1,引用计数加1。
3、当每一帧过后 AutoreleasePool调用clear函数,将存放的ref的引用计数减1。这里的每一帧可以理解为每一个画面的切换。

测试代码基于cocos2d-x v3.3:
文件:ActionTest.h
#ifndef __ACTIONTEST_H__
#define __ACTIONTEST_H__

#include "cocos2d.h"
#include <iostream>

USING_NS_CC;

class ActionTest :public Layer{
public:
	CREATE_FUNC(ActionTest);

	bool init();

private:
	void moveByAndMoveTo();
	Sprite* _pk1;
	Sprite* _pk2;
};
#endif
实现类:ActionTest.cpp
#include "ActionTest.h"

bool ActionTest::init(){

	auto s = Director::getInstance()->getWinSize();
	_pk1 = Sprite::create("pk.png");	//创建节点,_pk1引用计数加1
	CCLOG("pk1 ref count is %d",_pk1->getReferenceCount());
	_pk1->setAnchorPoint(Vec2(0.5,0.5));
	_pk1->setPosition(Vec2(s.width/2,s.height/2));
	_pk1->retain();		//调用retain(),_pk1引用计数加1
	CCLOG("pk1 ref count is %d",_pk1->getReferenceCount());

	auto moveByAndMoveToItem = MenuItemFont::create("moveByAndMoveToTest",CC_CALLBACK_0(ActionTest::moveByAndMoveTo,this));

	auto menu = Menu::create(moveByAndMoveToItem,nullptr);
	menu->alignItemsVertically();
	addChild(menu);

	return true;

}

void ActionTest::moveByAndMoveTo(){
	auto s = Director::getInstance()->getWinSize();
	auto scene = Scene::create();
	auto layer = Layer::create();

	_pk2 = Sprite::create("pk.png");
	_pk2->setColor(Color3B::GREEN);
	_pk2->setPosition(Vec2(s.width,s.height / 2));
	//创建Node,_pk2引用加一
	CCLOG("pk2 ref count is %d",_pk1->getReferenceCount());
	CCLOG("pk1 ref count is %d",_pk1->getReferenceCount());
	scene->addChild(layer);
	layer->addChild(_pk1);
	layer->addChild(_pk2);
	//添加父类,_pk2,_pk1引用加一
	CCLOG("pk2add ref count is %d",_pk1->getReferenceCount());
	CCLOG("pk1add ref count is %d",_pk1->getReferenceCount());

	//MoveBy是向量改变值,沿着向量路径运动
	auto mBy = MoveBy::create(3,Vec2(s.width/2,s.height/2));

	//MoveTo是移动到特定点
	auto mTo = MoveTo::create(3,Vec2(s.width / 2,s.height / 2));
	_pk1->runAction(mTo);
	_pk2->runAction(mBy);
	//执行动作引用加一
	CCLOG("pk2action ref count is %d",_pk1->getReferenceCount());
	CCLOG("pk1action ref count is %d",_pk1->getReferenceCount());
	Director::getInstance()->pushScene(scene);
}
注意:在init方法调用retain方法,是因为 调用init时_pk1的创建引用计数加一,但是其它类再引用_pk1时,引用数会变为0,因为autoreleasepool的cleae将引用计数减1,要再调用retain保持引用数大于0,不然会出现异常"reference count should greater than 0"

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