Search code examples
iphoneioscocoa-touchcore-graphicscore-text

Memory Management in Core Graphics Libraries


I'm a little bit confused on how handle memory management when dealing with graphics libraries, particularly some CoreText objects. For instance, I want to create a property for a CTFontRef, but really am not sure at all how I should declare it.

1) Should I treat it like a primitive and do @property(nonatomic)? Or should I not declare it as a property at all?

2) I assume I have to do CFRelease(myFont) in dealloc when I'm through with it? How do I release it properly

3) In the following method below, am I handling things properly? The CTFontRef is returned but isn't autoreleased. Do I need to worry about this?

- (CTFontRef) loadCustomFontWithName:(NSString *)fontName ofType:(NSString *)type attributes:(NSDictionary *)attributes
{
    NSString *fontPath = [[NSBundle mainBundle] pathForResource:fontName ofType:type];

    NSData *data = [[NSData alloc] initWithContentsOfFile:fontPath];
    CGDataProviderRef fontProvider = CGDataProviderCreateWithCFData((CFDataRef)data);
    [data release];

    CGFontRef cgFont = CGFontCreateWithDataProvider(fontProvider);
    CGDataProviderRelease(fontProvider);

    CTFontDescriptorRef fontDescriptor = CTFontDescriptorCreateWithAttributes((CFDictionaryRef)attributes);
    CTFontRef font = CTFontCreateWithGraphicsFont(cgFont, 0, NULL, fontDescriptor);

    CFRelease(fontDescriptor);
    CGFontRelease(cgFont);

    return font;
}

Overall, just a little confused on how to think about managing memory from lower level libraries like CoreGraphics or CoreText and would appreciate it if someone could tell me a good way to think about it.


Solution

  • Core foundation memory management is bit different. You don not create property with retain/ copy for those objects.

    When ever you use create and copy with CFObjects you have CFRelease it. To retain things there will be a method(eg: CGPDFPageRetain(pageRef)) to retain .

    look at this reference for more details.