2015-06-30 54 views
0

下面是一些示例代码:如何正确使用CFRetain和CFRelease?

@interface Foo : NSObject 
{ 
    CFAttributedStringRef m_foo; 
} 
@property (nonatomic, assign) CFAttributedStringRef foo; 
@end 

@implementation Foo 
@synthesize foo = m_foo; 

- (id)initWithAttributedString:(CFAttributedStringRef)attributedString 
{ 
    self = [super init]; 
    if (self == nil) 
     return nil; 

    if (attributedString != NULL) 
    { 
     self.foo = CFAttributedStringCreateCopy(NULL, attributedString); 
    } 

    return self; 
} 

- (void)dealloc 
{ 
    if (self.foo != NULL) 
     CFRelease(self.foo); 

    [super dealloc]; 
} 

@end 

的XCode警告我,潜在的内存泄漏在CFAttributedStringCreateCopyCFRelease两者。为什么?

编辑:如果我直接使用成员变量m_foo它纠正了问题。我有财产的内存管理语义错误吗?

+0

您还可以使用ARC和免费桥接将其直接转换为NSAttributedString并为您管理内存 – SomeGuy

回答

2
  1. 不能使用与像的malloc,免费,CFRetain,CFRelease,CFCopy,CFCreate等必须直接使用实例变量(即,使用m_foo代替self.foo手工存储器管理功能属性setter/getter方法)

  2. 如果foo是一个读/写属性,那么您必须提供一个自定义setter实现来正确处理内存管理。

例如,和setter是副本:

- (void)setFoo:(CFAttributedStringRef)newValue { 

    CFAttributedStringRef oldValue = m_foo; 
    if (newValue) { 
     m_foo = CFAttributedStringCreateCopy(NULL, newValue); 
    } else { 
     m_foo = NULL; 
    } 

    if (oldValue) { 
     CFRelease(oldValue); 
    } 
} 

如果foo并不需要是公共财产,那么你可能只想摆脱它,并专门使用实例变量。

相关问题