测试代码基于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" 总结
以上是内存溢出为你收集整理的[2]Cocos2d-x之引用计算(referenceCount)的增减时机全部内容,希望文章能够帮你解决[2]Cocos2d-x之引用计算(referenceCount)的增减时机所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)