Finding a Miss-Cast NSNumber in Cocoa

One of the things I'm going to miss moving to Swift is giving up the dynamic features of the Objective-C language. There's something compelling about being able to compose the behavior you want without defining and elaborate class ontology first.

I had a situation recently with a large, legacy application that had a tricky bug wherein an NSNumber managed to get cast to an NSString and assigned to the text propery of a UILabel. Of course, this caused an "unrecognized selector" when "length" was invoked on the NSNumber instance. Finding it was tricky because the exception was being thrown in UIKit code and looking through debugger the model objects thought they had NSStrings.

Rather than spending ages going through hundreds of properties on dozens of classes, I decided to take advantage of the Objective-C runtime and add a length method to the NSNumber class so that I could set a breakpoint and find which property it was.

As it turns out, if you want the NSNumber class to work with a UILabel, there are four methods you need to add which you can forward to NSString, much like you could do in Ruby with forwarding. Once you've done that, you can actually change the text of the description in a way that makes the numbers visually standout in the UI.

It's kind of a silly project, but it's kind of a fun thing you can do with Objective-C. I've linked the GitHub project for the experiment below.

Finding-NSNumbers GitHub Project

Home