How to create an NSIndexPath and specify its components

- by

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:

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

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

// current indexPath
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

// make a new indexPath and add 1 to the row of the previous one
NSIndexPath *indexPath2 = [NSIndexPath indexPathForItem:(indexPath.row + 1) inSection:indexPath.section];

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

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];

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.