tags:

views:

34

answers:

2

I have this method

-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(CFStringRef) path
{

   // bla bla
   // at some point I have

   CGContextRef myOutContext = CGPDFContextCreate (dataConsumer, &inMediaBox, NULL);

   // and then I have to return the value
    return myOutContext;
}

The problem is that myOutContext was not released and will leak.

if I put a CGContextRelease (myOutContext) before the return, then the reference will arrive invalid at the caller...

How do I solve that? Doing return [myOutContext autorelease]; will not work, as I suspected and tested.

thanks.

+1  A: 

Because your method has "Create" in its name, it's expected that the caller will be responsible for releasing the object. See http://developer.apple.com/library/ios/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-103029.


Update: Because this is a method and not a function, you should change it to start with "new" as described at http://developer.apple.com/library/ios/documentation/cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html#//apple_ref/doc/uid/20000043-SW1.

Robot K
thanks. I did that but Xcode gives me two errors. The first one on return myOutContext line (potential leak of object created on line ... - referring to the line where myOutContext was created) and the other error on the caller when I try to release the object, after using it (incorrect decrement of the reference count of an object that is not owned at this point by the caller)...
Digital Robot
Ah yes, you've created a method, not a function. Rename your method `newPDFContext:path` and the analyzer should stop complaining.
Robot K
Or you could ignore those analyzer warnings. They cancel each other out.
Robot K
ahhh... thanksssssssss!!!!
Digital Robot
+1  A: 

You need to follow memory conventions. Your method has the word "create" in it, which means that whoever calls that method is responsible for calling CGContextRelease on it when they are done with it. If you don't like that idea, then you need to find some way of knowing when the caller is done with it.

Ed Marty
thanks. Please read the commend I have done for Robot K
Digital Robot