Tag Archives: NSIndexPath

How to create an NSIndexPath and specify its components

On occasion we need to create an NSIndexPath manually, with components we specify (such as a row or a section). There’s a method for that: indexPath:forItem:inSection.

Here’s how you create an indexPath for row 0, section 0:

The method takes two integers. You can even take an existing indexPath, then add or subtract values to the new indexPath, like so:

How to pass an Index Path to another table

Say you have a central array somewhere and would like display this in more detail via two table view controllers. Instead of passing only the relevant information, you want to pass the entire index path from table1 to table2 and beyond.

You can pass data in the prepareForSegue:sender method and let the Storyboard to the heavy lifting:

Here we instantiate a new Table2 object on which myIndexPath is a property. Then we set it to our own table’s selected indexPath. In Table2 we can then pick it up and read out the array’s property.

Note that the didSelectRowAtIndexPath method of the table view can be completely empty for the data to be passed on. In fact, should you try an pass data in this method it won’t be available until the table is drawn.