Tuesday, June 18, 2024
HomeComputer programmingCreate NSIndexPath for UITableView in iPhone/iPad App

Create NSIndexPath for UITableView in iPhone/iPad App

Once you get past basic table view applications on the iPhone or iPad, you may run into the need to create an instance of NSIndexPath. NSIndexPath is an interesting class that stores the path to get to something in a nested set of collections. In an iPhone UITableView application, NSIndexPath is central as it provides a reference to the section of the table and the specific row of interest. There is a trick to creating an instance yourself. Read on to find out how.

If you need to make your own NSIndexPath object, you’ll probably check Apple’s documentation for NSIndexPath and realize that something funky is going on. There doesn’t appear to be a way to set the section and row parameters.

The trick is that there is a UIKit addition to NSIndexPath through the super cool use of an Objective-C category. This addition adds a class method for creating a UITableView compatible NSIndexPath in one easy step:

NSIndexPath *myIndexPath = [NSIndexPath indexPathForRow:row inSection:section];

That’s it. Memory management is left up to the coder.

Quinn McHenry
Quinn McHenry
Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.


Please enter your comment!
Please enter your name here

Most Popular


Recent Comments

error: Content is protected !!