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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »

Price Scanner via MacPrices.net

B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more

Jobs Board

Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.