5

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.

KexAri
  • 3,867
  • 6
  • 40
  • 80

2 Answers2

7

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).

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • And see, on this topic, my book: http://www.apeth.com/iOSBook/ch17.html#_using_a_cabasicanimation – matt May 24 '15 at 17:11
0

I don't think you need to remove it at all in this case.

In your completion handler, you're removing the layer from its superlayer, and you didn't hold onto the layer anywhere else. The layer hierarchy is the only thing retaining your layer so when you remove it from the hierarchy the layer will be deallocated.

Any animations added to the layer should also be deallocated.

bdrell
  • 194
  • 2
  • 5