Debugging with GDB: Print-Object and UIView recursiveDescription

In the post Debugging with GDB: Introduction to Commands, Print and Print-Object I covered the basics of the command line inteface in GDB. In this post I’ll show you a trick to print out the entire view hierarchy for UIView objects.

In Objective-C, all objects (derived from NSObject) have a description method, which returns an NSString describing the object. When using GDB, you can print the description using print-object, for example, let’s use the interface definition below to look at a few descriptions:

@interface SandboxViewController : UIViewController <UITextFieldDelegate>
  UITextField  *username;
  UIButton     *testButton;
  UILabel      *label;
  UIView       *view;

When stopped on a breakpoint in the SandboxViewController object, GDB can display information on each object:

Note, po is equivalent to print-object.

Print-Object and recursiveDescription

When working with UIView objects, there is an additional method for obtaining information, recursiveDescription. When using print-object and calling this method you can see the entire view hierarchy for the object.

With the SandboxViewController object defined above, in the loadView method I created a UIView as follows:

[self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];

Within GDB, when on a breakpoint within the SandboxViewController object, I can now view the entire view hierarchy as follows:

The same idea works for a UIView that is not associated with a view controller. Using the view defined below, and the label added as a subview:

// Create UIView
view = [[UIView alloc] initWithFrame: CGRectMake(10, 10, 300, 50)];
[[self view] addSubview:view];
// Add label to UIView
UILabel *tmplabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 280, 80)];    
[tmplabel setTextColor:[UIColor whiteColor]];
[tmplabel setTextAlignment:UITextAlignmentLeft];
[tmplabel setText: @"Enter your password:"];
[view addSubview:tmplabel];

Here is the recursive description:

  1. Thanks! I’ve been looking for something like that.

  2. A quick tip..
    You can print the UI hierarchy in any stackframe..
    po [[[[UIApplication sharedApplication]windows] objectAtIndex:0] recursiveDescription]

  3. Thank you for great posting. Figured this out a few days ago with ling to site – hope this was no copyright violation site.

Comments are closed.