Xcode 4 静态分析器在我的代码中报告了一些误报。有什么办法可以压制他们吗?
4 回答
我找到了一个解决方案:可以通过以下方式避免误报(如 Apple 单例设计模式):
#ifndef __clang_analyzer__
// Code not to be analyzed
#endif
Analyzer 不会分析这些预处理器指令之间的代码。
看看这个页面,它展示了如何使用几个#defines来注释objective-c方法和参数,以帮助静态分析器(clang)做正确的事情
http://clang-analyzer.llvm.org/annotations.html
从该页面:
Clang 前端支持 GCC 样式属性和编译指示形式的多个源代码级别注释,这有助于使 Clang 静态分析器的使用更加有用。这些注释既可以帮助抑制误报,也可以增强分析器发现错误的能力。
在这里查看我的答案。您可以在文件中添加编译标志,静态分析器将忽略它们。这对于您不关心的第三方代码可能更好,而不是您正在编写的第一方代码。
大多数时候,使用 CF_RETURNS_RETAINED 之类的东西并遵循“创建”规则对我有用,但我遇到了一个我无法抑制的情况。终于通过查看llvm源码找到了抑制分析器的方法:
https://llvm.org/svn/llvm-project/cfe/trunk/test/ARCMT/objcmt-arc-cf-annotations.m.result
“测试以查看我们在存储指向全局的指针时是否抑制错误。”
static CGLayerRef sSuppressStaticAnalyzer;
static CGLayerRef sDmxImg[2][2][1000]; // a cache of quartz drawings.
CGLayerRef CachedDmxImg(...) // which lives for lifetime of app!
{
...
CGLayerRef img = sDmxImg[isDefault][leadingZeroes][dmxVal];
if ( !img )
{
NSRect imgRect = <some cool rectangle>;
[NSGraphicsContext saveGraphicsState];
CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGLayerRef cgLayerRef = CGLayerCreateWithContext(ctx, imgRect.size, NULL);
CGContextRef layerCtx = CGLayerGetContext(cgLayerRef);
[NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort:layerCtx flipped:YES]];
... draw some gorgeous expensive Quartz stuff ...
img = cgLayerRef;
sDmxImg[isDefault][leadingZeroes][dmxVal] = cgLayerRef;
sSuppressStaticAnalyzer = cgLayerRef; // suppress static analyzer warning!
[NSGraphicsContext restoreGraphicsState];
}
return img;
}
出于某种原因,分配给静态数组并不会抑制警告,但分配给普通的旧静态 'sSuppressStaticAnalyzer'会。顺便说一句,使用 CGLayerRef 是我发现重绘缓存图像的最快方法(除了 OpenGL)。