Home > iphone > How to get all indexPaths from a UITableView?

How to get all indexPaths from a UITableView?

I find this a very basic question, but somewhat difficult to find in the Apple documentation. The answer is not found in the NSIndexPath Class Reference, but in the NSIndexPath UIKit Additions. That’s why I think some people would not know about the following method which allows us to get a specified indexPath from a UITableView.

The method is:

+ (NSIndexPath *)indexPathForRow:(NSUInteger)row inSection:(NSUInteger)section

And it returns an indexPath object initialized with the indexes of a specific row and section in a table view.

With this method we will be able to retrieve all the indexPaths from a table view performing a loop like this:

NSInteger nSections = [tableView numberOfSections];
for (int j=0; j<nSections; j++) {
  NSInteger nRows = [tableView numberOfRowsInSection:j];
  for (int i=0; i<nRows; i++) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:j];
    //Do something with your indexPath. Maybe you want to get your cell,
    // like this:
    //UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  }
}

I hope this helps. If you find an easier way, please tell me.

  • Facebook
  • Twitter
  • Google Plus
  • Meneame
  • Add to favorites
  • RSS
  • BarraPunto
Categories: iphone Tags:
  1. elbolsa
    May 28th, 2009 at 09:07 | #1

    yes, i have always asked myself about this subject. thank you very much!!

  2. Metodij Zdravkin
    May 17th, 2011 at 07:57 | #2

    Excellent post… been searching google for this and there is not a single other post that answers this question.

    Added

    cell.accessoryType = UITableViewCellAccessoryNone;

    in the last for cycle and got a custom check view.

    Thanks a lot!!!

  3. Faris
    September 30th, 2015 at 03:03 | #3

    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];

  1. No trackbacks yet.


four × 2 =