OneGuyInDc
OneGuyInDc

Reputation: 1565

Memory leak in CABasicAnimation

The following code points to a memory allocation leak (using the allocation tool in profiler) - Can someone point out why - I am using a CABAsicAnimation to rotate a UIImageView

-(void)SetGaugeToValueInAngles: (int)newValue
{

    static int oldValue = 0;

    int delta = newValue - oldValue;

    CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    [rotate setDelegate:self];
    rotate.fromValue = [NSNumber numberWithFloat:oldValue/57.2958];
    rotate.removedOnCompletion = NO;
    rotate.fillMode = kCAFillModeForwards;

    rotate.toValue = [NSNumber numberWithFloat:  newValue/57.2958];

    rotate.duration = 10.0; // seconds

    [self.UIImageViewPressureMark.layer addAnimation:rotate forKey:nil]; // "key" is optional

    NSLog(@"Old Value %d New Value %d", oldValue, newValue);

    oldValue = newValue;
}

Upvotes: 1

Views: 1702

Answers (2)

sunqingquan
sunqingquan

Reputation: 1

You should call removeAnimationForKey when you release instance of this class. Do as following 1.change

[self.UIImageViewPressureMark.layer addAnimation:rotate forKey:nil];

to

[self.UIImageViewPressureMark.layer addAnimation:rotate forKey:@"myAnimation"]; 

in your method "SetGaugeToValueInAngles"

2.call following method when you relase instance of this class

- (void)invalateAnimation
{
    [self.UIImageViewPressureMark.layer removeAnimationForKey:@"myAnimation"];
    self.UIImageViewPressureMark.layer = nil;
}

Upvotes: 0

peko
peko

Reputation: 11335

If you set removeOnCompletion to NO the layer will retain the animation until you remove it.

You should either set removedOnCompletion to YES, or check to see if the layer already has the animation and remove it when you add the next newValue

Upvotes: 3

Related Questions