Performing Static Code Analysis

Find flaws—potential bugs—in the source code of a project with the static analyzer built into Xcode. Source code may have subtle errors that slip by the compiler and manifest themselves only at runtime, when they could be difficult to identify and fix.

bullet
To find flaws in your source code using the static analyzer
  1. Choose Product > Analyze.

  2. Select an analyzer message in the issue navigator.

  3. Click the corresponding message in the source editor.

  4. Use the pop-up menu in the analysis results bar above the edit area to study the flow path of the flaw.

  5. Edit the code to fix the flaw.

    The video shows the process of looking at a flaw in the source file SKTText.m.

The Xcode static analyzer parses the project source code and identifies these types of problems:

  • Logic flaws, such as accessing uninitialized variables and dereferencing null pointers

  • Memory management flaws, such as leaking allocated memory

  • Dead store (unused variable) flaws

  • API-usage flaws that result from not following the policies required by the frameworks and libraries the project is using

You can suppress false positive messages from the analyzer using assertions, attributes, or pragma directives.

When you analyze a project for the first time, you may uncover a lot of issues. But if you run the static analyzer regularly and fix the flaws it uncovers, you should see fewer problems in subsequent analyses. Analyze early; analyze often. It’s good for the code.

Note that if the static analyzer reports no problems, you can't assume that there are none. The tool cannot necessarily detect all the flaws in the source code.