gpt4 book ai didi

objective-c - 构建和分析泄漏检测的误报?

转载 作者:太空狗 更新时间:2023-10-30 03:59:39 25 4
gpt4 key购买 nike

我有这个代码:

- (CGImageRef)createImageWithContext:(CGContextRef)context
{
return CGBitmapContextCreateImage(context);
}

- (void)fooWithContext:(CGContextRef)context
{
CGImageRef imgRef = [self createImageWithContext:context];
CGImageRelease(imgRef);
}

这是一个在启用了 ARC 的 Xcode 中构建的 Objective-C 项目。 Build 和 Analyze 报告了两个错误:一个在 CGBitmapContextCreateImage 行上标识潜在的泄漏,一个在 CGImageRelease 上指出“调用者此时不拥有的对象的引用计数的不正确减少”。

如果我将这两个功能合二为一:

- (void)fooWithContext:(CGContextRef)context
{
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGImageRelease(imgRef);
}

我没有收到任何警告。

静态代码分析错误?或者我在这里遗漏了什么?

最佳答案

根据标准的 Cocoa 命名约定,以单词 create 开头的方法应该返回一个非拥有的引用。您正在返回一个保留对象,但您应该返回一个非保留对象。因此,当分析器查看 -createImageWithContext: 时,它发现它应该返回一个非保留对象,但实际上返回的是一个保留对象。因此第一个警告。

-fooWithContext: 中,它会查看您的代码并说“嘿,根据我的命名约定,createImageWithContext: 应该返回一个非拥有引用。但是随后他们正在发布他们不拥有的东西!这很糟糕!”因此第二次警告。

您可以通过将 -createImageWithContext: 的名称更改为以 new 开头的名称来解决此问题,例如 -newImageWithContext:。或者您可以使用 cf_returns_retained macro 注释该方法向静态分析器指示该方法正在返回拥有的引用。

关于objective-c - 构建和分析泄漏检测的误报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8438249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com