Peaks and Troughs

I was talking to my wife the other night and she was telling me about an article she was reading. At one point in this article she had learned something that blew her mind, and she was surprised further when she discovered the target audience of the publication was for “beginners”.

This put me in mind of something I’ve always felt with respect to my own education, that is to say I like taking beginner classes and reading beginner articles. But I have had trouble putting the reason into words.

Chances are you’ve had a lot of teachers. Stop and think about it. I have been to one junior high, three high schools, two colleges, and two universities and would not care to estimate the total number of teachers because odds are the estimate would be too low.

Right from the time you left grade school and entered junior high it has been a different teacher/educator/mentor/guru/wikipedia editor/your title here, for everything you have undertaken to learn and at every level of expertise. Each one of these educators has spoken from a different base of experience.

Last night it occurred to me that this broad variety of input we receive can be thought of as being somewhat like a frequency graph. Everything in the x axis of this graph is an area of experience and the y axis is your level of expertise.

That x axis is your collection of jedi powers that you use to sell yourself to potential employers, colleagues, friends and lovers. Many of us tend to put all our effort into pushing these skills further into the Y and wanting to push those peaks and achieve that higher level of proficiency is not a bad thing, but we tend to get a little myopic.

You are going to get a lot of reinforcement in certain areas of that x axis. When you put all your attention into pushing that skill further your eyes are going to start to glaze the second you hear/see/read something that is familiar. So stop focusing so much on proficiency.

Stop assuming you know everything. You and your teachers have probably had some of the same teachers so you are going to get that reinforcement. But the breadth of their experience means that some of what may sound familiar but is different in subtle and very important ways and you don’t want to miss that.

Those troughs are the low hanging fruit in your tool kit and the smallest thing learned can have profound effects on the peaks next to it. So don’t dismiss that class with 60% overlap, read chapter one or that beginners article, you may learn something. At worse, you learn that you did in fact know what you thought you knew.

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.