2

私はこの方法を持っています(他の誰かがそれを書きました!)

- (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;
}

これで、Analyzeを実行して、3つのメモリリーク警告が表示されました。

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

誰かが私にここで何が必要/何をすべきかを教えてもらえますか?CF関数名にcreateまたはcopyを使用して、すべてをCFReleaseする必要があることを理解しています。私が理解していないのは、PDFをリリースしても、関数の最後でそれを返すことができる方法です。私は何が欠けていますか?ありがとうございました。

4

4 に答える 4

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
于 2012-06-17T17:59:45.537 に答える
5

pdfを受け取ったコードは、それを使い終わった後にCFReleaseする責任があります。Cocoaとは異なり、CFは自動解放をサポートしていないため、CF関数から返されるオブジェクトは、呼び出し元が所有し、処理する必要のあるオブジェクトです。

createCFオブジェクトを返す関数には、またはに応じて名前を付ける必要があるという命名規則もあります。copy

于 2012-06-14T17:30:02.493 に答える
3

関数で作成したオブジェクトを返したいので、関数自体に適切な名前を付けて、返すオブジェクトを解放する必要があることを示す必要があります。

の代わりに、関数またはgetPdfを呼び出すことができます。これにより、呼び出し元は、完了時に呼び出す必要があることを通知し、Analyzeの要求も満たします。createPdfcopyPdfCFRelease

于 2012-06-14T17:30:54.900 に答える
-1
- (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 autorelease];
}

これで問題は解決できると思います。

于 2014-06-06T07:46:31.420 に答える