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:

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

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 Reply to Bob Easterday Cancel reply