27

I have a method that returns a CGMutablePathRef, something like this:

- (CGMutablePathRef)somePath;  
{  
    CGMutablePathRef theLine = CGPathCreateMutable(); 

    CGPathMoveToPoint(theLine, NULL, 50, 50);  
    CGPathAddLineToPoint(theLine, NULL, 160, 480);  
    CGPathAddLineToPoint(theLine, NULL, 270, 50);

    return theLine;  
}  

The Xcode/Clang static analyzer warns that there's a potential leak. The docs say to call CGPathRelease() but where would I put that?

If I put that before the method returns won't that cause theLine to disappear before it's returned to it's caller?

willc2
  • 38,991
  • 25
  • 88
  • 99

2 Answers2

29

If a method name begins with new, clang will expect it to return an object with a retain count of 1. In other words, renaming the method from somePath to newSomePath will quiet the Analyzer.

If you actually want to autorelease the CGPathRef, you might be able to cast it to an NSObject and then call autorelease. I know that works for CFTypes, I'm honestly not sure if CGPathRef qualifies.

benzado
  • 82,288
  • 22
  • 110
  • 138
  • Too bad that this doesn't work with C-functions that return CG objects. :( – Pascal Mar 09 '12 at 23:14
  • 3
    @Pascal Is the analyzer complaining about a C-function? There are naming conventions for those, too. I think names containing `Copy` or `Create` are expected to return retained items. – benzado Mar 10 '12 at 16:54
  • Awesome, using `create...` as function name did the trick, thanks! – Pascal Mar 12 '12 at 19:16
  • @benzado Thank you for saving me. Using create on my C-function worked like a charm. Is this specific to Apple's compiler or C in general? – Johnny May 17 '12 at 03:44
  • @benzado +1 amazing piece of knowledge, do you have a reference to the documentation that mentions this? Thanks. – Unheilig Jun 29 '13 at 16:50
  • I can't remember any reading any documentation but I remember it being mentioned in one of the WWDC 2011 or maybe 2012 videos. One of the ones about ARC, sorry I can't remember the exact session. – neilkimmett Dec 30 '13 at 15:16
  • 1
    I know this is kind of an old question but its still valid, and for those coming across it now, FYI: it seems 'create' is no longer a valid option in the latest versions of Xcode. 'new' works as well as 'copy'. – kdbdallas Jun 15 '15 at 16:24
8

How about creating a mutablepath, passing it to your building function, then using and releasing it:

CGMutablePathRef mPath = CGPathCreateMutable();
[buildPath:mPath]; //adds reusable lines etc
...do something with it...
CGPathRelease(mPath);
Mobs
  • 1,572
  • 12
  • 17