[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"



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值