Refactoring an Objective-C Method
Posted: August 4th, 2009 | Author: Gareth Townsend | Filed under: Code, Objective-C, iPhone | Comments OffSometimes you stumble across code that makes you think “WTF?”. Recently I discovered this Objective-C method in an iPhone project. I’ve renamed the method names and variables to protect the innocent.
This method is called when a user taps a button inside a table cell. The purpose of the method is to find the table cell that the button belongs to, and then call didSelectRowAtIndexPath on that table cell.
Disregarding the fact that this methods purpose makes didSelectRowAtIndexPath one very bloated method, there are a few other improvements we can make to it.
First, this method uses a C-style for loop. Objective-C 2.0 supports fast enumeration. Fast enumeration is faster, looks better, and throws an exception if you attempt to modify the collection while it is being enumerated.
Because NSArray has a well defined order, and enumeration proceeds in that order, we can simply count the index.
We now have more lines of code than the original, but the intent is somewhat clearer. The implementation of this method however, still relies on a string comparison to find the correct table cell, which is not ideal.
Using our knowledge of the view hierarchy we can re-implement this method to forgo enumeration altogether.
Knowing that our button is inside a table cell we can ask it for its superview. Once we have the table cell, we can ask for its indexPath. We can then call didSelectRowAtIndexPath directly using the indexPath.