Category Archives: iOS

More Fun With Exceptions in Cocoa

Ever wonder what the problem is when Xcode is catching on an exception deep within the cocoa libraries because you’ve got break on all exceptions on? Many of these can be a little confusing because despite the fact that an exception was thrown your app seems to run fine afterwards.

I was curious too, but Apple is using C++ exceptions in many of the core libraries so there’s no object to catch and break on to grab the info (unless you want to convert the class to Objective C++ and use C++ exceptions yourself).

You can however dig into the stack trace and get the exception information from the registers themselves1.
These are the steps I used.

  1. Select the __cxa_throw stack frame in the Debug Navigator.
  2. In the variables view of the debug, where it normally says “Auto”, you want to select “All”.
  3. Under “General Purpose Registers” we are looking for two specific registers2.
    1. r3 which I will call the exception reason.
    2. r10 which I will call the exception data.
  4. Right click on each of these registers and select “View Value As” -> “Custom Type‚Ķ”
  5. In the popover that appears change (unsigned int)$r3 to (char *)$r3

Thats it, you should now see two environment variables in your list with intelligible output. I was trying to instantiate a UIImage from NSData I got from the web and there was an error in the meta data so I got the following

  • $r3 = "Duplicate property or field node"
  • $r10 = "pmtm:Version"

If you want to ignore the inner library exceptions just select “Objective-C” when creating your exception breakpoint.

  1. The exception I was encountering and investigating was in the ImageIO framework which is used by CoreImage, UIImage, etc to create images. I don’t know if the registers used vary from framework to framework. 

  2. Register r12 also holds a bunch of data but I have no clue what it is. I was originally using call (void)printf("%s", `$r12`) to inspect the register contents so a bunch of text came out that looked like backslash hex encoded UTF8 with a bunch of extra chars. decoding it as a UTF8 string did not produce better results. My suspicion is that it is a pointer to the exception handler but the suspicion is pretty baseless, If anyone knows drop me a line. 

Exceptions in Objective-C


We in the Objective-C community have a lot of habits that get considered ‘good practice’ simply because someone at sometime told us something was good or bad without explaining why and for some unknown reason we took this knowledge an ran with it until it became canalized. A perfect example of this is exceptions.

Background on rant

I was reviewing some crash logs and found some low hanging fruit I thought I’d tackle. The error was a nil insertion issue, simple enough to fix. The piece of code looked like this.

NSString *bodyText = pendingSharingItem.title;
NSArray *activityItems;

if (pendingSharingItem.linkURLString)
    activityItems = @[bodyText, [NSURL URLWithString:pendingSharingItem.linkURLString]];
    activityItems = @[bodyText];

The biggest issue here is that were checking for the presence of one thing and inserting another. This is silly behaviour and should be avoided; but it was an understandable mistake given that the pendingSharingItem.linkURLString in this case is initialized with a valid URL and locally is only ever assigned valid URL constants. But what if pendingSharingItem.linkURLString is being manipulated somewhere else, through a dangling pointer perhaps? There are a number of ways to fix this, on of which is a @try-catch block.

Enter the neck beard

“No one who writes Objective-C uses exceptions”1 this or something similar is a common refrain in the community and for a long time it was a totally valid statement as exceptions are implemented using setjmp & longjmp and originally the runtime handled this slowly and offered little support for performing cleanup afterwards. This meant people coming from other languages where exception handling was used for recovery and flow control were in for a really bad time.

Trimming the beard

I racked my brain from where I got this idea that exceptions were bad. When the “exceptions are bad” mentality took root in my skull I had no knowledge of the technical reasons above. Also The issue mentioned above was largely addressed in GCC 3.32 and has only improved since.

The runtime uses exceptions, clearly there are cases where it is prudent to catch them. Apple says array bound issues and such are a good reason to handle exceptions. Also if handling exceptions will not affect your user by putting the app into a bad state then not crashing is probably a good choice.

The Objective-C Phrasebook has an excellent treatment on exceptions and mentions that on 64 bit systems, entering a try/catch block is dirt cheap and throwing is expensive but safe3


So, am I going to start using exceptions? Yes and No. I know the 64 bit system thing applies to OS X so I’ll be catching exceptions there. However, I don’t know that the performance improvements are present on the iPhone and performance is still a concern and while slower devices like the iPhone 4 are still around so I’ll just check each item before inserting it for the time being. I do know I’ll feel sillier the next time I hesitate to catch one though.

  1. If this were true how’d I encounter this issue in the firstplace? 

  2. I can think of 3 or 4 people I know that might have been hacking in Objective-C at that time, where most of you dear readers probably started sometime after 2006 ;) 

  3. Until now I’ve been careful to mention catching exceptions only . Personally I think throwing exceptions as a method of control flow is overused and unless you are writing a framework for others to use you have no business throwing them; check out NSError instead. 

iOS 5 and UITableView prototype cells

I was reading the post here which talks about how to use prototype cells, one of the new features in iOS 5.

In the section “Creating the TableView Datasource” we see this snippet of code in


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    CarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[CarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault

    // Do stuff

    return cell;

This code is absolutely correct. But you want to use and explore all the goodies that iOS 5 has to offer you right? So here’s another one. I’ve been targeting iOS 5 prior to its public debut back in October, and like all of Apple’s betas before it, answers were hard to come by due to the NDA. So I spent a bunch of time digging around in the headers. One of the the things I came across was this little gem in UITableView.h

// Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier; 

// when a nib is registered, calls to dequeueReusableCellWithIdentifier: with the 
// registered identifier will instantiate the cell from the nib if it is not already in the reuse queue
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_5_0);

When you create a prototype cell in a xib or storyboard that cell is already registered with the table view. So all you need to do is dequeue the cell, if one does not exist the tableView will instantiate one for you. So the above snippet now becomes this.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    CarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Do stuff

    return cell;

If you are stuck targeting iOS versions < 5 then you still need to do the nil check of course. Alternatively you could check out Matt Drance’s book iOS Recipies which illustrates how to get similar behavior out of your tableviews.