Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to remove CABasicAnimation when the animation is finished?

I am animating a layer like so to change the background color:

CALayer *layer = [CALayer layer];
            layer.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height);
            layer.backgroundColor = [UIColor yellowColor].CGColor;
            [self.view.layer insertSublayer:layer atIndex:0];
            [CATransaction begin];
            CABasicAnimation *animation = [CABasicAnimation animation];
            animation.keyPath = @"position.y";
            animation.byValue = @(-self.view.bounds.size.height);
            animation.duration = 0.4;
            animation.fillMode = kCAFillModeForwards;
            animation.removedOnCompletion = NO;
            self.animating=YES;
            [CATransaction setCompletionBlock:^{
                NSLog(@"finished");
                self.view.backgroundColor=[UIColor yellowColor];
                [layer removeFromSuperlayer];
                self.animating=NO;
            }];
            [layer addAnimation:animation forKey:@"slide"];
            [CATransaction commit];

When I'm finished I set the actual background color of the UIView and then remove the layer. Do I need to call something like [self.view.layer removeAllAnimations]; in the completion block to remove the animation too or is it removed automatically? Just thinking about memory management.

like image 200
KexAri Avatar asked May 24 '15 16:05

KexAri


1 Answers

There is no need to say

animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;

...if you structure your animation and layer correctly from the start. That entire dance is based on an old misconception of how animation works. It is still unfortunately often seen floating around the Internet, but it is wrong and was always wrong. It's better to learn to do this properly (by setting the layer to its final property value as the animation begins).

like image 102
matt Avatar answered Sep 24 '22 23:09

matt