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)引用。