In this section, we will take a look at how we can use the Clang Static Analyzer tool to examine the syntax of our code for bugs.
There may be times when you want to examine the syntax of your code for bugs. This is where the Static Analyzer tool comes handy. This tool was first introduced back in Xcode 3.x, and opened and displayed the build results in a new window.
Xcode 4 allows you to perform the analysis of your code, examine the results, and apply the fixes to your source files all within the Xcode 4 workspace environment.
To run the Static Analyzer, perform the following simple steps:
ViewController.m
implementation file.btnTapHere
method and enter the following modified code snippet:- (IBAction)btnTapHere:(id)sender { UIColor *color; int colorIndex; #ifdef DISPLAY_FIRSTNAME NSLog(@"Using the Firstname field."); NSString *greeting = [NSString stringWithFormat: @"Welcome to Xcode 4 Cookbook series %@", txtFirstname.text]; #else NSLog(@"Using Firstname and Surname fields."); NSString *greeting = [NSString stringWithFormat: @"Welcome to Xcode 4 Cookbook series %@ %@", txtFirstname.text, txtSurname.text]; #endif if (colorIndex == 1) { lblOutput.textColor = [UIColor redColor]; } else if (colorIndex == 2) { lblOutput.textColor = [UIColor blueColor]; } else if (colorIndex == 2) { lblOutput.textColor = [UIColor purpleColor]; } else { lblOutput.textColor = [UIColor blueColor]; } lblOutput.text = greeting; lblOutput.font = [UIFont boldSystemFontOfSize:21]; }
When the analyzer finishes checking your code for problems, the issues navigator opens automatically and shows you a list of issues that were found within your project. This is shown in the following screenshot:
Clicking on an issue within the left-hand pane will open the file in question, and display the problem that has been marked with a blue triangle. Clicking on this triangle will display the faulty flow of logic that has been identified and detected by the static analyzer, as can be seen in the preceding screenshot.
The static analyzer has flagged that the colorIndex
variable has a potential error. This is due to the fact that the variable was not initialized upon declaration and contains some random value.
You will also notice that the analyzer provides additional detail when you click on the message bubbles, and displays the control flow, as can be seen by the arrows. This provides you with a full diagnosis of the bug. Many of the issues that are reported by the static analyzer tool have this information and make the analysis and fixing of these errors much easier.
If you would like to find out more information about the Static Analyzer, you can refer to the Apple developer documentation located at http://developer.apple.com/library/ios/#recipes/xcode_help-source_editor/Analyze/Analyze.html.