Static Analysis in XCode

Slalom Consultant Greg Martin

Greg Martin is a member of the Slalom National Mobility team which incubates emerging technology solutions in areas such as mobility, user experience and alternative application hosting.

Before most of my project time was devoted to iPhone development I worked mostly in .Net.  I love the Microsoft development tools and there are a lot of things that I still miss not having on a daily basis.  One of the things that I thought I was missing was FxCop (which was later integrated into Visual Studio 2005).  FxCop is a static analysis tool which allows you to find potential issues in your code before it goes to test.

In the Mac and iPhone development world there is a similar tool called Clang which in the most recent release of XCode (3.2) has also been integrated.  Static analysis is even more useful in Objective-C development because unlike .Net, proper memory management is in the hands of the developer and this is where Clang really shines, especially if you are just learning.

Here is a very simple example that really highlights the power of this tool.

First, there are two ways to run analysis.  Either manually kick it off from the build menu by choosing “Build and Analyze” (or by pressing Shift+Command+A) or turn on “Run Static Analysis” in your project settings to that it will run at every build:

build and analyze

run static analyzer

Lets create a very simple snippet of code that illustrates a very common memory management mistake in Objective-C.  The code below shows an instance of NSMutableString being allocated and initialized, used but then never released:

NSMutableString allocated and initialized

When we build, the static analyzer automatically finds our issue and points it out:

static analyzer finds issue

Clicking the icon gives you more detail on the logic flow that would occur to cause the leak, this is helpful when you have complex logic in your app and need to better understand when the issue will occur:

 

more detail about the logic flow

And just to round out the example, here is the proper fix for the issue:

Static Analysis Issue Fixed– Greg

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: