Instruments—Leaks
Instruments is a powerful
suite of debugging and testing tools. Tools include Activity Monitor, CPU Sampler, Leaks,
Object Allocations, Core Animation, OpenGL ES, and System Usage (Figure 12).
Note
For
more information on Instruments, refer to Apple’s documentation
“Instruments User Guide,” available online or via the Instruments Help
menu.
However, one tool worth
introducing you to here is Leaks. You can use Leaks without knowing
much about it. The Leaks instrument allows you to easily find memory
leaks in your application. It tells you how many leaks occurred, each
leak’s size, the address of the leak, and the leaked object’s type.
Using Leaks is fairly intuitive—rather than explaining, let me simply
explain by example through the following application.
In the following task, you
find memory leaks using the iPhone Simulator.
Find a Memory Leak on iPhone Simulator
Create a new Utility application named Sieve.
Create a new Objective-C class named FooBar.
Open FlipsideViewController.m and implement the viewDidAppear method (Listing 6). Don’t forget to import FooBar.h.
Listing 6. The viewDidAppear method
-(void) viewDidAppear:(BOOL) animated { FooBar * myFooBar = [[FooBar alloc] init]; }
|
Select
Edit Active Scheme from the pull-down menu. Click Launch in the left
column; then select the Instruments radio button and select Leaks from
the pull-down menu. Click OK to save your changes to the scheme.
Run
the application. Ignore the warning informing you that you never use
the FooBar instance in viewDidAppear. Note that when you’re using
Instruments, Xcode will run the iPad Simulator rather than the iPhone
Simulator. You’ll also see the Instruments application automatically
launch.
Click Info and Done repeatedly for about 30 seconds. When finished, click Stop in the Instruments window (Figure 13).
Click Leaks, and a detailed list of the leaked objects appears. Click one of the leaked objects.
Select View | Extended Detail from the main menu, and a call stack appears on the window’s right (Figure 14).
Double-click one of the leaks, and the source code will display with the line allocating and initializing FooBar (Figure 15).