如何正确释放CF对象?

Tre*_*zar 2 memory-management objective-c core-foundation ios

我有这种方法(别人写了!)

- (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;
}
Run Code Online (Sandbox Code Playgroud)

现在,我运行了Analyze并获得三个内存泄漏警告:

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
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我这里需要/应该做些什么?我知道我应该在CF函数名称中创建或复制CFRelease所有内容.我不明白的是我如何发布pdf并仍能在函数结束时返回它.我错过了什么?谢谢.

Col*_*ler 6

您需要clang源注释,如此处所示http://cocoasamurai.blogspot.com/2012/01/clang-source-annotations.html

    #import <AppKit/AppKit.h>
@interface NSColor (CWNSColorAdditions)
-(CGColorRef)cw_cgColor CF_RETURNS_RETAINED;
@end
Run Code Online (Sandbox Code Playgroud)


Mic*_*itz 5

收到pdf的代码有责任在完成后将其发送给CFRelease.与Cocoa不同,CF不支持自动释放,因此从CF函数返回的任何对象都是调用者拥有并必须处理的对象.

它也是命名约定,那些返回CF对象的函数应该用create或者相应地命名copy