Xcode’s Analyzer (and how to prevent it)

Guides | Tutorial By 5 years ago

Xcode’s “Analyzer” is normally a great way to determine where most memory leaks will occur in your project without actually running it. If you follow Apple’s Memory Management Guidelines┬áthe Analyzer is pretty accurate. By no means is it a replacement for the Profiler, but offers some quick checks.

The Analyzer generates it’s warnings based on method and function names. If you have a function called “init*” or “copy*” it will assume the object returned is retained, whereas if your function returns an object and doesn’t follow that naming convention it’s assumed the object is autoreleased. Of course there are many more rules around the way the Analyzer works, but these are some basics.

The same is applied to C functions, but the naming conventions change a little. If the function has “Create” in it (such as CGPathCreateWithRect) the returned object is assumed to be retained, and if you give an object to a function that has “Release” in it (such as CGPathRelease), the object is assumed to be released in here.

In an app I was working on a while back, I was using the UIGetScreenImage function to get a screenshot of the device as an image. This one is part of Apple’s Private API so I must declare it in my code. Even though this looks as if the returned CGImageRef is autoreleased, it is actually retained. A better name to describe this function would be UICreateScreenImage. Of course, when CGImageRelease-ing the returned image, the Analyzer will throw up some warnings as the function doesn’t follow the regular naming conventions.

If you get a situation like this (hopefully with another person’s framework/library, I recommend following all the naming conventions on your own code), you can prevent the Analyzer running over any bits of code wrapped inside the following preprocessor if statement:

#ifndef __clang_analyzer__
	//	Something I don't want the Analyzer to look at...

So my piece of code becomes