我使用了cocos2d 2.0,在精灵动画切换时观察到崩溃。这是代码
@interface PPActor : CCSprite
{
CCRepeatForever *pirateIdleAnim;
CCSequence *mPirateDashAnim;
CCRepeatForever *mPirateRocketAnim;
}
//案例1:第二次播放时崩溃
-(void)loadAnim
{
CCAnimate *AnimActions = [CCAnimate actionWithAnimation:animation];
id calFun = [CCCallFunc actionWithTarget:self selector:@selector(dashAnimDone)];
mPirateDashAnim = [CCSequence actions:AnimActions, calFun, nil];
mPirateDashAnim.tag = kTagDashAnim;
}
-(void)runDashAnim
{
[self stopActionByTag: kTagDashAnim];
[self runAction:mPirateDashAnim];
}
//案例2:没有崩溃,但显示内存泄漏...(使用保留)
-(void)loadAnim
{
CCAnimate *AnimActions = [CCAnimate actionWithAnimation:animation];
id calFun = [CCCallFunc actionWithTarget:self selector:@selector(dashAnimDone)];
mPirateDashAnim = [[CCSequence actions:AnimActions, calFun, nil] retain];
mPirateDashAnim.tag = kTagDashAnim;
}
-(void)runDashAnim
{
[self stopActionByTag: kTagDashAnim];
[self runAction:mPirateDashAnim];
}
//案例3:再次发现崩溃
-(void)loadAnim
{
CCAnimate *AnimActions = [CCAnimate actionWithAnimation:animation];
id calFun = [CCCallFunc actionWithTarget:self selector:@selector(dashAnimDone)];
mPirateDashAnim = [CCSequence actions:AnimActions, calFun, nil];
mPirateDashAnim.tag = kTagDashAnim;
}
-(void)runDashAnim
{
[self stopActionByTag: kTagDashAnim];
[self runAction:[mPirateDashAnim copy]];
}
如何克服此崩溃和内存泄漏?
答案 0 :(得分:1)
你总是在runDashAnim之前调用loadAnim吗?因为动作是一次性对象。当动作结束时,它会自行释放。你必须再次创建动作。
请不要遵循建议保留操作的“最佳做法”。这是不好的做法,因为除非你知道一个动作的内部行为(即代码),否则存在创建内存泄漏或崩溃的风险,因为并非所有动作都可以以这种方式重用。