如何在方法返回CFObject时释放(ARC)CoreFoundation对象?

时间:2012-12-19 12:02:22

标签: iphone ios xcode

我有类似于下面的CFObject返回方法

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

}

这里我得到了内存泄漏,我没有释放CFRelease(as3);对象,因为它是一个返回方法。有没有办法解决内存泄漏问题?

1 个答案:

答案 0 :(得分:1)

幸运的是,NSAttributedStringNSMutableAttributedString分别与其核心基金会同行CFAttributedStringRefCFMutableAttributedStringRef免费桥接。这意味着您可以创建一个CFAttributedStringRef并简单地将其转换为NSAttributedString指针,然后调用NSAttributedString方法就可以了。

所以只需将桥梁投射到圆弧

NSAttributedString *nsString = (__bridge transfer NSAttributedString*)as3

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