2013-02-04 98 views
1

我正在使用下面的代码生成PDF,但会导致内存泄漏,任何人都可以帮忙吗?下面给出代码 。由于CTFontRef导致的内存泄漏

- (void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect { 


    NSMutableAttributedString *string = [[[NSMutableAttributedString alloc] 
             initWithString:textToDraw] autorelease]; 

    // make a few words bold 

    CTFontRef helveticaBold = CTFontCreateWithName(CFSTR("Helvetica-Bold"), 8.0, NULL); 

    [string addAttribute:(id)kCTFontAttributeName 
        value:(id)helveticaBold 
        range:NSMakeRange(0, [string length])]; 

    // add some color. 
    if (_flag == 1) { 

     [string addAttribute:(id)kCTForegroundColorAttributeName 
         value:(id)[UIColor whiteColor].CGColor 
         range:NSMakeRange(0, [string length])]; 


    } else { 

     [string addAttribute:(id)kCTForegroundColorAttributeName 
         value:(id)[UIColor blackColor].CGColor 
         range:NSMakeRange(0, [string length])]; 
    } 

    // layout master 
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string); 

    CGMutablePathRef framePath = CGPathCreateMutable(); 
    CGPathAddRect(framePath, NULL, frameRect); 

    // Get the frame that will do the rendering. 
    CFRange currentRange = CFRangeMake(0, 0); 
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL); 
    CGPathRelease(framePath); 

    // Get the graphics context. 
    CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

    // Put the text matrix into a known state. This ensures 
    // that no old scaling factors are left in place. 
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity); 
    CGContextSetRGBFillColor(currentContext, 0, 0, 0, 1.0); 

    // Core Text draws from the bottom-left corner up, so flip 
    // the current transform prior to drawing. 
    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2); 
    CGContextScaleCTM(currentContext, 1.0, -1.0); 

    // Draw the frame. 
    CTFrameDraw(frameRef, currentContext); 

    CGContextScaleCTM(currentContext, 1.0, -1.0); 
    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2); 

    CFRelease(frameRef); 
    //CFRelease(stringRef); 
    CFRelease(framesetter); 

} 

我调用这个函数的几个时间,而一代

PDF和每到这个时候导致内存泄漏。

回答

6

CTFontCreateWithName遵循创建名称管理规则,即如果你创建它,你拥有它,你必须释放它,当你完成:

CFRelease(helveticaBold); 
+0

它给我的警告的功能隐式声明在C99无效的东西。 –

+0

对不起,我的错。只需使用CFRelease。 –

+0

你是否知道你是真棒;)它只是工作完美谢谢4这个伟大的帮助干杯:P –