I have this method (someone else wrote it!)
- (CGPDFDocumentRef)getPdf {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"myLocalFileName.pdf"];
NSURL *pdfURL = [NSURL fileURLWithPath:pdfPath];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
return pdf;
}
Now, I’ve ran Analyze and get three memory leak warnings:
Call to function 'CGPDFDocumentCreateWithURL' returns a Core Foundation object with a +1 retain count
Object returned to caller as an owning reference (single retain count transferred to caller)
Object leaked: object allocated and stored into 'pdf' is returned from a method whose name ('getPdf') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'. This violates the naming convention rules given in the Memory Management Guide for Cocoa
Could someone please educate me what needs/should be done here ? I understand that I should CFRelease everything with create or copy in the CF function name. What I don’t understand is how I can release pdf and still be able to return it at the end of the function.
What am I missing ?
Thank you.
It is the responsibility of the code receiving the pdf to CFRelease it after they are done with it. Unlike Cocoa, CF does not support autoreleasing, so any object that is returned from a CF function is an object that the caller owns and must deal with.
It is also naming convention that those functions that return a CF object should be named accordingly with
createorcopy