ios開發(fā)動畫造成內(nèi)存泄露的解決方法之一

ios開發(fā)在使用動畫的時(shí)候,嘗嘗出現(xiàn)動畫造成的內(nèi)存泄露,主要是應(yīng)為蘋果本身動畫代理為強(qiáng)引用,如下圖所示


截圖

我碰到這類問題我的解決方法如下:

//創(chuàng)建動畫
- (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"];
}

主要因?yàn)橛袝r(shí)候使用的時(shí)候在動畫結(jié)束的時(shí)候在代理中沒有移除動畫,移除動畫問題即可解決

//動畫執(zhí)行結(jié)束
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (flag) {
        //動畫完成后移除動畫,避免內(nèi)存泄露
        [self.addLabel.layer removeAnimationForKey:@"moveToCart"];
        self.addLabel.hidden=YES;
        self.clickBuyCart();
    }
}

移除動畫可以解除動畫動畫對當(dāng)前的self強(qiáng)引用,從而打破循環(huán)引用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。