简体   繁体   中英

How to release(ARC) the CoreFoundation object when the method returns CFObject?

I have the CFObject returning method similar to below

-(CFMutableAttributedStringRef)getAttStrForArray:(NSArray*)substrings forString:(NSString*)aStr
{

   CFMutableAttributedStringRef as3 = CFAttributedStringCreateMutable(NULL, 0);
    CFAttributedStringBeginEditing(as3);
    CTFontRef font = CTFontCreateWithName(CFSTR("HelveticaNeue-Bold"), 12.5, NULL);
    CFAttributedStringReplaceString(as3, CFRangeMake(0, 0), (__bridge CFStringRef)aStr);
   ......
   CFAttributedStringEndEditing(as3);
    //CFRelease(as3);
   return as3;

}

here i'm getting memory leak that i hav't released the CFRelease(as3); object since it's a return method. is there any way to fix the memory leak?

Fortunately, NSAttributedString and NSMutableAttributedString are both toll-free bridged to their Core Foundation counterparts CFAttributedStringRef and CFMutableAttributedStringRef respectively. That means you can create, for example, a CFAttributedStringRef and simply cast it to an NSAttributedString pointer, and then calling NSAttributedString methods on it will work.

so just bridge cast it to the arc

NSAttributedString *nsString = (__bridge transfer NSAttributedString*)as3

-(NSMutableAttributedString*)getAttStrForArray:(NSArray*)substrings forString:(NSString*)aStr
{
   CFMutableAttributedStringRef as3 = CFAttributedStringCreateMutable(NULL, 0);
   //...
   return (__bridge transfer NSAttributedString*)as3;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM