Search code examples
objective-cxcode4.5

Will this code leak if I remove CFRelease?


    CTFontRef font = CTFontCreateWithName((__bridge  CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
    NSRange  rangeHighlight = NSMakeRange(range.location, substringToHighlight.length);
    if (font) {
        [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)font range:rangeHighlight];
        CFRelease(font); //Is this still necessary?
    }

I copy and paste this code from https://github.com/mattt/TTTAttributedLabel

  CTFontRef font = CTFontCreateWithName((CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
  if (font) {
    [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)font range:boldRange];
    [mutableAttributedString addAttribute:@"TTTStrikeOutAttribute" value:[NSNumber numberWithBool:YES] range:strikeRange];
    CFRelease(font);
  }

When I do that I got an error saying that I got to use the keyword __bridge. What is it? I put it and compile error stop. But then I wonder if I still need to use CFRelease(font)

In addition

  1. What is CF in CFRelease?
  2. What is __bridge?
  3. Should I do CFRelease(font) after using __bridge?
  4. Where can I learn more about this?

Solution

  • Yes you still need to use CFRelease(font).

    You are still the one creating the font so you need to release it as well. The __bridge part is related to how the font name is retained or not.

    1. CF is short for Core Foundation, the C level API that Foundation is built upon. CFRelease is how you release a Core Foundation object.

    2. __bridge tells ARC how it should retain or not retain an objects when translating it to a Core Foundation object. This question explains the different __bridge types.

    3. You should still release (explained above).

    4. Search for "Core Foundation". The Design Concepts explains the general design.