TweetFollow Us on Twitter

A simple debugging tool for Cocoa

Volume Number: 19 (2003)
Issue Number: 12
Column Tag: Programming

A simple debugging tool for Cocoa

Another weapon in the fight against bugs

by Steve Gehrman

Here's the problem: You write an application, test it, fix the bugs and everything works great while testing in-house. But, the moment you send it to the customer you get a ton of bug reports.

How could this be? You tested the code thoroughly, and you've been running the application for months throughout the development process. You're now getting bug reports you've never seen before. What happened?

The problem lies in the fact that it's just not possible for the developer or even a small team of in-house testers to uncover all the bugs no matter how hard they try. Software is just too complex, and there are just too many variations in machines, OS versions, and interactions with other installed software to catch everything.

So, what can you do? The only solution is to have your users help in the testing/debugging process. These users/testers are commonly referred to as beta testers. There's only one problem with this solution. Your beta testers aren't developers, and have no clue how the code works, so the bug reports you receive may not be easy to decipher or reproduce. What you really need is a fool proof way for a user to report a problem automatically with information in a form that helps the developer determine what went wrong.

In this article, I explain a simple technique for doing this. Using this technique, when a problem occurs in your application, a window will appear with information describing what happened, and a stack trace of where the problem occurred. There is also a button in the window to automatically email this information to the developer. That way, all the developer has to do is check their email, examine the reports, and fix the bugs. Sounds cool, right?

The key to this debugging tool is exceptions. Most Cocoa objects will throw an exception when passed a bad parameter or when something unexpected happens. Catching and displaying exception information is the key to this debugging aid. Catching exceptions can't find every type of software bug in your application, but it will uncover a surprising number of problems and uncover lots of trouble spots in your code. I've been using this code in my own application, "Path Finder," for two years now, and it has proven indespensible.

The remainder of this article explores the code used to do this and explains how it works. All the code is downloadable in a simple example application. If you're like me and like to see the working code before reading the rest of the article, download the example application here from the MacTech website at www.mactech.com/src/19.12.

The Code:

Cocoa has two built in classes for exception handling: NSException and NSExceptionHandler. These two classes are located in the ExceptionHandling.framework. The first step is to add this framework to your application. I'm using XCode, so to do this I go to the "Project" menu and choose "Add Frameworks..." and navigate to /System/Library/Frameworks/ and choose ExceptionHandling.framework.

Let's start by looking at the NSExceptionHandler class. NSExceptionHandler is really simple and does the work of telling us when an exception has occurred in our application. All we need to do is create a delegate object that will be sent a message when an exception occurs.

I created a class called NTExceptionHandlerDelegate to do this. Here's the code, it's very short.

@implementation NTExceptionHandlerDelegate
- (id)initWithEmail:(NSString*)emailAddress;
{
    self = [super init];
    
    _emailAddress = [emailAddress retain];
    
    [[NSExceptionHandler defaultExceptionHandler] setDelegate:self];
    [[NSExceptionHandler defaultExceptionHandler] setExceptionHandlingMask:
       NSLogAndHandleEveryExceptionMask];
    
    return self;
}
- (void)dealloc;
{
    [[NSExceptionHandler defaultExceptionHandler] setDelegate:nil];
    [_emailAddress release];
    [super dealloc];
}
// used to filter out some common harmless exceptions
- (BOOL)shouldDisplayException:(NSException *)exception;
{
    NSString* name = [exception name];
    NSString* reason = [exception reason];
    
    if ([name isEqualToString:@"NSImageCacheException"] ||
        [name isEqualToString:@"GIFReadingException"] ||
        [name isEqualToString:@"NSRTFException"] ||
        ([name isEqualToString:@"NSInternalInconsistencyException"] && [reason hasPrefix:
           @"lockFocus"])
        )
    {
        return NO;
    }
    
    return YES;
}
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldLogException:(NSException *)exception 
   mask:(unsigned int)aMask;
{
    // this controls whether the exception shows up in the console, just return YES
    return YES;
}
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldHandleException:(NSException *)exception 
   mask:(unsigned int)aMask;
{
    // if the exception isn't filtered by shouldDisplayException, display the information to the user
    if ([self shouldDisplayException:exception])
        [[NTExceptionPanelController alloc] initWithException:exception emailAddress:_emailAddress];
    
    return YES;
}
@end

For the init method of NTExceptionHandlerDelegate, I pass it an email address. This is the email address where you want to receive the exception reports. You need to allocate one of these objects somewhere in your code. In the sample application, I allocate it in +[MyDocument initialize]. If you run the sample application, be sure to change the email address so you will receive the emailed reports.

Next, I call two methods using the shared default NSExceptionHandler object:

[[NSExceptionHandler defaultExceptionHandler] setDelegate:self];
[[NSExceptionHandler defaultExceptionHandler] setExceptionHandlingMask: 
   NSLogAndHandleEveryExceptionMask];

The call to setDelegate sets this instance of NTExceptionHandlerDelegate as the NSExceptionHandler's delegate. The second call to setExceptionHandlingMask tells NSExceptionHandler which exceptions I'm interested in handling. I pass NSLogAndHandleEveryExceptionMask to tell it to send me every exception.

There were a few harmless exceptions that were happening frequently in Path Finder that I decided to filter out. That way my email box doesn't get full of emails that I've already determined to be OK. The exception filtering happens in the method shouldDisplayException. You may choose to remove or modify this code.

In order for the NTExceptionHandlerDelegate instance to receive the exceptions, it must implement two methods found in the informal protocol located in NSExceptionHandler.h.

@interface NSObject(NSExceptionHandlerDelegate)
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldLogException:
   (NSException *)exception mask:(unsigned int)aMask;   
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldHandleException:
   (NSException *)exception mask:(unsigned int)aMask;
@end

These are the messages sent by the NSExceptionHandler to the delegate when an exception occurs. In the code above you can see that in the method exceptionHandler:shouldLogException:, I just return YES. This tells the NSExceptionHandler to log the exception in the console. In the next method exceptionHandler:shouldHandleException:mask I call the code to display the exception to the user in a window. This is where the magic happens. This window is handled in by the NTExceptionPanelController class.

Let's look inside NTExceptionPanelController to see what it does.

- (id)initWithException:(NSException*)exception emailAddress:(NSString*)emailAddress;
{
    self = [super init];
    
    _displayFont = [[NSFont fontWithName:@"Monaco" size:10.0] retain];
    _emailAddress = [emailAddress retain];
    
    // load the nib
    if (![NSBundle loadNibNamed:@"NTExceptionPanel" owner:self])
    {
        NSLog(@"Failed to load NTExceptionPanel.nib");
        NSBeep();
    }
    else
    {
        [self displayCrashReport:exception];
        
        // center the window, show the window
        [window center];
        [window makeKeyAndOrderFront:nil];
    }
    
    return self;
}

The init call loads the nib containing the window, and if successful, calls [self displayCrashReport:exception]. The window loaded from the nib contains a single NSTextView. displayCrashReport's job is to fill that text view with the information extracted from the exception. NTExceptionPanelController has a simple helper method called displayText to write a string into the NSTextView.

Here's the code:

- (void)displayCrashReport:(NSException*)exception;
{
    NSMutableArray *args = [ NSMutableArray array ];
    NSString* appName = [self applicationName];
    NSString* stackTrace;
    
    // display instructions
    [self displayText:appName];
    [self displayText:[NSString stringWithFormat:@" has encountered an unexpected error.  
       Please email this report to %@ so it can be fixed in the next release.", _emailAddress]];
    [self displayText:@"\r\r"];
    
    // display version
    [self displayText:appName];
    [self displayText:@": "];
    [self displayText:[NTUtilities applicationVersion]];
    [self displayText:@"\r\r"];
    
    // display OS version
    [self displayText:[NTUtilities OSVersion]];
    [self displayText:@"\r\r"];
    
    [self displayText:[exception name]];
    [self displayText:@"\r\r"];
    [self displayText:[exception reason]];
    [self displayText:@"\r\r"];
    
    stackTrace = [[exception userInfo] objectForKey:NSStackTraceKey];
    if (stackTrace)
    {
        // add the process id
        [args addObject:@"-p"];
        [args addObject:[[self applicationProcessID] stringValue]];
        
        {
            // must add each stack trace as individual arguments
            NSScanner *scanner = [NSScanner scannerWithString:stackTrace];
            NSString* output;
            
            NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
            
            while (YES)
            {
                if ([scanner scanUpToCharactersFromSet:whitespace intoString:&output])
                    [args addObject:output];
                else
                    break;
            }
        }
        
        _atosTask = [[NTTaskController alloc] initWithDelegate:self];
        [_atosTask runTask:NO toolPath:@"/usr/bin/atos" directory:@"/" withArgs:args];
    }
}

We start by displaying the application name and instructions to the user telling them what has occurred and what to do next. Next we display the version of the application, the version of the OS, the exception name, and the exception reason. Next is the stack trace. Inside the exeption userInfo dictionary is an NSString with the key NSStackTraceKey. This string looks something like this:

0x8c7a1f04  0x97e54804  0x97df1820  0x01e58aa0  0x930f9cac  0x9311a3ec  
0x9315e54c  0x930f36b8  0x9315e168  0x9312de6c  0x930c102c  0x930a8e20  0x930b1dac  
0x9315fc58  0x00117f74  0x000038e0  0x00003760  0x00001000

That isn't too useful. What we really need is for those numeric addresses to be converted into symbols. Fortunately, there is a built in unix command line tool that does this called "atos". Open the Terminal and type "man atos" for more information.

In order to run "atos" we first need convert the string of addresses in to an array of individual address strings. This is used as the parameter to "atos". atos takes this array of addresses and converts each one to a human readable symbol. In Cocoa this is easily accomplished using an NSTask. In this code I'm using a wrapper around NSTask called NSTaskController which makes running an NSTask even easier. Basically, it runs the task and sends us the output and takes care of all the details automatically. Next, the code takes the output and adds it to the windows NSTextView. Look at the documentation on NSTask and look at the code of NSTaskController to see how this works. It's very straightforward.

Here's some sample output from atos. Given the input string of: "0x8c7a1f04 0x97e54804 0x97df1820 0x01e58aa0 0x930f9cac 0x9311a3ec 0x9315e54c 0x930f36b8 0x9315e168 0x9312de6c 0x930c102c 0x930a8e20 0x930b1dac 0x9315fc58 0x00117f74 0x000038e0 0x00003760 0x00001000", we get this:

_NSExceptionHandlerExceptionRaiser (in ExceptionHandling)
+[NSException raise:format:] (in Foundation)
-[NSCFArray objectAtIndex:] (in Foundation)
-[MyDocument exception1Action:] (in MyDocument.ob) (MyDocument.m:72)
-[NSApplication sendAction:to:from:] (in AppKit)
-[NSControl sendAction:to:] (in AppKit)
-[NSCell _sendActionFrom:] (in AppKit)
-[NSCell trackMouse:inRect:ofView:untilMouseUp:] (in AppKit)
-[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] (in AppKit)
-[NSControl mouseDown:] (in AppKit)
-[NSWindow sendEvent:] (in AppKit)
-[NSApplication sendEvent:] (in AppKit)
-[NSApplication run] (in AppKit)
_NSApplicationMain (in AppKit)
_main (in main.ob) (main.m:13)
start (in ExceptionHandlerExample)
start (in ExceptionHandlerExample)
0x00001000 (in ExceptionHandlerExample)

That's a whole lot easier to understand than the string of addresses.

So, we are almost done. We have a window which contains all the information on the exception and a stack trace telling us exactly where the exception occurred. Now all we need to do is email this information to the developer.

Cocoa has a very simple interface for sending an email using the class NSMailDelivery. NSMailDelivery is part of the Message.framework, so you will need to add the Message.framework to your project. I'm using XCode, so to do this I go to the "Project" menu and choose "Add Frameworks..." and navigate to /System/Library/Frameworks/ and choose Message.framework.

- (void)emailAction:(id)sender;
{
    BOOL mailSent=NO;
    NSString *subject = [NSString stringWithFormat:@"%@ exception report", [self applicationName]];
    mailSent = [NSMailDelivery deliverMessage:[textView string] subject:subject to:_emailAddress];
    if (!mailSent)
        NSBeep();  // you may want to handle the error
    
    [window close];
}

The email button in the window is set to send the action emailAction. In email action I construct a string for the message subject and use the contents of the NSTextView as the email body. Sending the email requires just one line of code:

mailSent = [NSMailDelivery deliverMessage:[textView string] 
subject:subject to:_emailAddress];

Summary:

So, that's all there is too it. Add this to your application, send it out to beta testers and get back accurate reports of trouble spots in your code. This debugging tool doesn't catch all types of bugs. There are many types programming errors that don't throw exceptions and therefore won't be detected by this system, but it is one more powerful tool in your arsenal against bugs.


Steve Gehrman is the founder and lead developer at CocoaTech. Feel free to contact Steve at steve@cocoatech.com.

 
AAPL
$99.18
Apple Inc.
-1.57
MSFT
$45.90
Microsoft Corpora
-0.46
GOOG
$568.27
Google Inc.
-9.09

MacTech Search:
Community Search:

Software Updates via MacUpdate

Cocktail Family License (5 Macs) 7.6.1 -...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
Cocktail 8.0 Beta 2 - General maintenanc...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
QuickBooks 2015 16.0.0.1352 R1 - Financi...
QuickBooks 2015 helps you manage your business easily and efficiently. Organize your finances all in one place, track money going in and out of your business, and spot areas where you can save.... Read more
Mac DVDRipper Pro 5.0.1 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
Apple OS X bash Update 1.0 - Fix for sec...
The OS X bash Update fixes a security flaw in the bash UNIX shell on OS X 10.9.5 (also on OS X 10.8 and 10.7 [see Related Links below]). OS X 10.9.5 or later Downloads for OS X 10.8 and OS X 10.7 in... Read more
SyncTwoFolders 2.0.5 - Syncs two user-sp...
SyncTwoFolders simply synchronizes two folders. It supports synchronization across mounted network drives and it is a possibility to run a simulation showing in a log what will be done. Please visit... Read more
FinderPop 2.5.7 - Classic Mac utility, n...
FinderPop is a Universal preference pane that extends OS X's contextual menus using a FinderPop Items folder much as the Apple Menu Items folder used to do for the Apple menu. It has other features... Read more
VueScan 9.4.45 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
LibreOffice 4.3.2.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
calibre 2.4 - Complete e-library managem...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more

Latest Forum Discussions

See All

iKeywi - Customizable 5-Row Keyboard (U...
iKeywi - Customizable 5-Row Keyboard 1.0 Device: iOS Universal Category: Utilities Price: $.99, Version: 1.0 (iTunes) Description: Want to add an extra row to your iPhone/iPad? One of the most popular keyboard extension in iOS... | Read more »
Manage Your Cloud – Wunderlist Now Suppo...
Manage Your Cloud – Wunderlist Now Supports Dropbox Posted by Jessica Fisher on October 1st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Nexticy Review
Nexticy Review By Jennifer Allen on October 1st, 2014 Our Rating: :: IDEAL FORM CREATIONiPad Only App - Designed for the iPad Nexticy allows you to make your own forms for research purposes or to organize your business better. It’s... | Read more »
Tiny Troopers: Alliance Marches onto the...
Tiny Troopers: Alliance Marches onto the App Store Tomorrow Posted by Jessica Fisher on October 1st, 2014 [ permalink ] Tiny Troopers: Alliance, by Kukouri, is a | Read more »
HeroCraft Introduces Unlimited Sequel to...
HeroCraft Introduces Unlimited Sequel to WW2: Sandbox. Strategy & Tactics Posted by Jessica Fisher on October 1st, 2014 [ permalink ] | Read more »
RGB Express Review
RGB Express Review By Jennifer Allen on October 1st, 2014 Our Rating: :: DELIGHTFUL PUZZLINGUniversal App - Designed for iPhone and iPad Guide trucks along their delivery routes in RGB Express, a testing but charming puzzle game... | Read more »
The Sagas of Fire*Wolf (Games)
The Sagas of Fire*Wolf 1.0 Device: iOS Universal Category: Games Price: $9.99, Version: 1.0 (iTunes) Description: | Read more »
BuggyFun Review
BuggyFun Review By Amy Solomon on October 1st, 2014 Our Rating: iPad Only App - Designed for the iPad BuggyFun allows children to create their own tracks for bugs to interact with for a unique open-ended experience.   | Read more »
Fold the Adventure Review
Fold the Adventure Review By Jennifer Allen on October 1st, 2014 Our Rating: :: AWKWARD FOLDSUniversal App - Designed for iPhone and iPad Fold pieces of paper to create platforms for a princely rabbit in this puzzle game; something... | Read more »
WW2: Sandbox. Strategy & Tactics (G...
WW2: Sandbox. Strategy & Tactics 1.0.0 Device: iOS Universal Category: Games Price: $9.99, Version: 1.0.0 (iTunes) Description: ***NOTE: Compatible with iPhone 4s and up, iPad 2 and up - may not work properly on earlier devices... | Read more »

Price Scanner via MacPrices.net

Amazon offers 13-inch MacBook Air for $899, $...
Amazon.com has the 13″ 1.4GHz 128GB MacBook Air on sale for $100 off MSRP including free shipping: - 13″ 1.4GHz 128GB MacBook Air: $899.99 Read more
Apple resting On Its iPhone Laurels? – The ‘B...
Apple calls its new iPhone 6 and 6 Plus “The Biggest Advancements in iPhone History,” but does reality live up to the hype? “Seldom have so many waited so breathlessly for so little,” tweeted veteran... Read more
Roundup of Apple Mac and iPad Education disco...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
Apple Boycotts German Magazine Computer Bild...
Apple has revoked its PR accreditation of Germany’s Computer Bild, Europe’s best-selling PC magazine, in reaction to Bild’s posting of a “#Bentgate” YouTube video. Axel Telzerow, editor in chief of... Read more
iPhone 6 & iPhone 6 Plus Available in Chi...
Apple has announced that iPhone 6 and iPhone 6 Plus will be available in China beginning Friday, October 17 from the Apple Online Store (http://www.apple.com), Apple’s retail stores, and an expansive... Read more
MacBook Airs on sale for $100 off MSRP, start...
Best Buy has the new 2014 MacBook Airs on sale for $100 off MSRP on their online store. Choose free home shipping or free local store pickup (if available). Prices valid for online orders only, in-... Read more
Apple Releases OS X Mavericks bash Update 1.0...
Apple has released a patch update for OS X Mavericks users to address the recently-detected “Shellshock” security bug in BSD UNIX’s bash shell. Apple says only a few Mac users who had manually... Read more
Pivotal Payments Ready for Apple Pay – FlexPo...
Pivotal Payments, a provider of merchant services and global payment processing solutions, has announced its proprietary FlexPoint platform will support credit and debit transactions through Apple’s... Read more
iStabilizer Announces Tabarm — First Friction...
iStabilizer, a specialist in universal lightweight compact tripods, steady cams, dollies, mounts, and remotes for smartphones, tablets, and cameras, announced today the iStabilizer tabArm, the first... Read more
IStabilizer Flex Smartphone Tripod Wins Usa T...
iStabilizer, a specialist in universal lightweight compact tripods, steady cams, and other products for smartphones, tablets, and cameras, has announced today that its iStabilizer Flex smartphone... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.