【问题标题】:Xcode analyzer complaining of CFContextRef stored in an "assign" @propertyXcode 分析器抱怨存储在“分配”@property 中的 CFContextRef
【发布时间】:2019-12-21 19:45:33
【问题描述】:

我有一个 Cocoa 类,它需要长时间保留位图上下文来进行像素操作。

@property (assign, nonatomic) CGContextRef cacheContext; // block of pixels

在我的班级初始化中:

// this creates a 32bit ARGB context, fills it with the contents of a UIImage and returns a CGContextRef
[self setCacheContext:[self allocContextWithImage:[self someImage]]];

在dealloc中:

CGContextRelease([self cacheContext]);

Xcode 分析器公司关于 init 泄漏类型为 CGContextRef 的对象,并且在 dealloc 中抱怨“不正确地递减不属于调用者的对象”。

我相信这一切都很好,并且运行良好。

我如何告诉 Xcode 这一切都好,而不是抱怨它?

【问题讨论】:

  • ARC 还是托管内存?另外,cacheContext getter 和 setter 的代码是什么?
  • 这是非 ARC 代码,getter/setter 只是 @property(assign, nonatomic) 提供的内置函数。在 init 中,警告是“'CGContextRef _Nullable' 类型的已分配对象在此执行路径中稍后未引用,并且保留计数为 +1”。确实,它没有被进一步引用(直到 dealloc),因为它现在存储在“assign”属性中,以供在类的其他地方使用。
  • 如果你使用生成的 getter/setting 那么你不需要nonatomic。试着把它拿出来看看是否有帮助。我还尝试删除assign 属性(它不会受到伤害),看看这是否让分析器高兴(一个问题是你的保留是不对称地完成的——保留的设置器应该在dealloc上释放,还有一个设置器不保留不应该释放)。
  • 删除分配和/或非原子没有帮助。我正在创建 CFContext 并将其简单地存储在分配属性中-实际上只是该类的局部变量。我在 dealloc 中正确地释放了它,以便它在我的类对象的生命周期中持续存在。我的 setter/getter 不应该保留或释放任何东西 - CFContextRef 归我所有,我需要释放它(我确实这样做了)。
  • ... 评论室用完了... 我的建议是将 setter 更改为 retain (或自己滚动以使用 CFRetain)然后 CGContextRef ctx = [self alloctContextWithImage:...]; self.cacheContext = ctx; CGContextRelease(ctx); 现在你使用平衡的保留/释放(您将来可能会避免出现错误!)

标签: xcode cocoa core-foundation analyzer


【解决方案1】:

好的,鉴于这里的讨论是我认为可以解决分析器投诉的方法,让您保留您的正式财产,并且不违反任何内存管理规则。

声明一个只读属性:

@property (readonly) CGContextRef cacheContext;

创建时直接分配 ivar

_cacheContext = [self allocContextWithImage:self.someImage];

dealloc发布它:

- (void)dealloc
{
    CGContextRelease(_cacheContext);
    [super dealloc];
}

【讨论】:

    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多