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:

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.

2 thoughts on “How to create an NSIndexPath and specify its components

  1. You are effectively allocating indexPath twice. The convenience method will return an allocated object. the above can be written simply as;

    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];

Add your voice!