NSIndexPath and row method

Tue, Aug 12

In working with the SimpledDrillDown example in the iPhone SDK, I was walking through the code in the RootViewController class. The interface definition is shown below:

1
2
3
4
@interface RootViewController:UITableViewController
{
DataController *dataController;
}

There is a method inside the class that looks as follows:

1
2
3
4
5
6
7
- (void)tableView:(UITableView *)tableView
  didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
...
detailViewController.detailItem = [dataController objectInListAtIndex:indexPath.row];
...
}

The last parameter to this method ‘indexPath’ is of type NSIndexPath . Now if you look at the class reference for NSIndexPath , you won’t find the ‘row’ method shown above? What’s up with that?

This is actually a great example of Objective-C categories in use (here is a link to a previous post on categories) The UIKit has extended the NSIndexPath class (without subclassing) through use of a category. The reason for this addition is to add support for identifying rows and sections in UITableView objects.

The addition consists of a class factory method indexPathForRow:inSection: which creates an NSIndexPath object when passed in row and section values. There are also two properties available to return the row index number and the section index number.

You can find all the specifics in NSIndexPath UIKit Additions .

4 comments

Thanks for helping me find the documentation for “row”.

This may be a great example of categories, but only if you know the secret. IMO, it demonstrates a real problem with the reference documentation. The UITableViewDataSource Protocol Reference (and others) lead me to the un-extended class and no idea why “row” is missing. It took a google search and this page for me to find out about UIKit Additions and “row”.

As an Objective-C newbie, I’ll ask why this is so much better than subclassing. If every Table View related use of NSIndexPath is going to use “row” and depend on it, why not just subclass NSIndexPath? Should I write my DataSource to expect NSIndexPaths that may or may not support row?

by LostOne on Sep 20, 2008. Reply #

Yep, I was confused as well! Very helpful information :-)

-cheers from julz @p

by julian skidmore on Jul 2, 2010. Reply #

Wow, years later and this issue just dumbfounded me. It took google for me to figure out where the ‘row’ property was coming from. Is there something that I am missing that would tell a developer that a Categoy has been used on NSIndexPath?

-Jason

by Jason Hanson on Dec 23, 2011. Reply #

Wish I had a good answer to that question. If memory serves me, the primary reason I wrote this post is that I was also surprised to read about the UIKit addition for NSIndexPath. You may of already bumped into this, however, there is also an NSString UIKit Additions

by John Muchow on Dec 23, 2011. Reply #

Leave a Comment