MatterGoal
MatterGoal

Reputation: 16430

Memory leak with Core Graphics cocoa

I can't understand what is leaking in this code. I get these 2 leaks:

enter image description here

I don't know how to give you more information than directly adding the code here:

    float value = [[dict objectForKey:@"value"] floatValue];
    UIColor *color = (UIColor*)[dict objectForKey:@"color"];
    NSString *type = [dict objectForKey:@"type"];

    CAShapeLayer *circle = [CAShapeLayer layer];
    circle.path = CGPathCreateWithEllipseInRect(CGRectMake(0, 0, LABELSIZE, LABELSIZE), nil);
    circle.fillColor = color.CGColor;
    circle.contentsScale = 2.0;

    CATextLayer *text = [CATextLayer layer];
    text.contentsScale = 2.0;
    text.string = [NSString stringWithFormat:@"%d%%",(int)value];
    text.frame = CGRectMake(0, LABELSIZE/2 - LABELFONTSIZE/2 -1.0, LABELSIZE, LABELFONTSIZE);
    text.fontSize = 10;
    text.alignmentMode = kCAAlignmentCenter;
    text.foregroundColor = [UIColor colorWithWhite:0.0 alpha:0.6].CGColor;
    text.font = (__bridge CFTypeRef)([UIFont fontWithName:@"Avenir-Medium" size:LABELFONTSIZE]);

    [circle addSublayer:text];

    if([type isEqualToString:@"IN"]){
        circle.position = CGPointMake(0, self.layer.frame.size.height / 2 - LABELSIZE/2);
    }else{
        circle.position = CGPointMake(self.layer.frame.size.width - LABELSIZE, self.layer.frame.size.height / 2 - LABELSIZE/2);
    }

    [self.labelsLayer addSublayer:circle];

Upvotes: 0

Views: 1308

Answers (2)

GxocT
GxocT

Reputation: 764

There are some ways to avoid leaking the memory:

Use CFAutorelease function (only available in iOS 7+ and Mac OS X 10.9+)

circle.path = CFAutorelease(CGPathCreateWithEllipseInRect(CGRectMake(0, 0, LABELSIZE, LABELSIZE), nil));

Create explicit variable and release it after assigning:

CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(0, 0, LABELSIZE, LABELSIZE), nil);
circle.path = path;
CGPathRelease(path);`

Upvotes: 1

Anoop Vaidya
Anoop Vaidya

Reputation: 46563

Your leak errors are due to

    circle.path = CGPathCreateWithEllipseInRect(CGRectMake(0, 0, LABELSIZE, LABELSIZE), nil);

As you know, CGXxx and CFXxx are not dealt with ARC, and you need to manually release the memory. So release the memory you created above.

EDIT: (As commented by Rob)

You have to call CGPathRelease(). For every Core Graphics method you call with "Create" or "Copy" in the name, you have to call the appropriate Core Graphics CGXXXRelease method manually (or, in some cases, you can transfer ownership to ARC).

Upvotes: 7

Related Questions