ios开发动画造成内存泄露的解决方法之一

2017-12-28  本文已影响0人  小歪子go

ios开发在使用动画的时候,尝尝出现动画造成的内存泄露,主要是应为苹果本身动画代理为强引用,如下图所示


截图

我碰到这类问题我的解决方法如下:

//创建动画
- (IBAction)clickShoppingCart:(id)sender {
    Weak(self);
    self.addLabel.hidden=NO;
    UIButton *button=(UIButton *)sender;
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.calculationMode = kCAAnimationPaced;
    pathAnimation.fillMode = kCAFillModeForwards;
    pathAnimation.removedOnCompletion = NO;
    pathAnimation.duration = 0.5;
    pathAnimation.repeatCount = 0;
    pathAnimation.delegate=weakself;
    CGMutablePathRef curvedPath = CGPathCreateMutable();
    CGPathMoveToPoint(curvedPath, NULL, self.picImageView.frame.origin.x, self.picImageView.frame.origin.y);
    CGPathAddQuadCurveToPoint(curvedPath,NULL,self.contentView.frame.size.width-80,0, button.center.x, button.center.y);
    pathAnimation.path = curvedPath;
    CGPathRelease(curvedPath);
    [self.addLabel.layer addAnimation:pathAnimation forKey:@"moveToCart"];
}

主要因为有时候使用的时候在动画结束的时候在代理中没有移除动画,移除动画问题即可解决

//动画执行结束
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (flag) {
        //动画完成后移除动画,避免内存泄露
        [self.addLabel.layer removeAnimationForKey:@"moveToCart"];
        self.addLabel.hidden=YES;
        self.clickBuyCart();
    }
}

移除动画可以解除动画动画对当前的self强引用,从而打破循环引用。

上一篇下一篇

猜你喜欢

热点阅读