Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does indexPath.row return?

i am reading the Big Nerd Ranch guide on Objective c programming and i have the code:

- (NSInteger) tableView:(UITableView *)tableView 
  numberOfRowsInSection:(NSInteger)section {

    return [self.tasks count]; 
}

- (UITableViewCell *) tableView:(UITableView *)tableView 
  cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    // Get a reusable cell
    UITableViewCell *c = [self.taskTable dequeueReusableCellWithIdentifier:@"Cell"];

    // This below is what i don't understand
    NSString *item = [self.tasks objectAtIndex:indexPath.row];
    c.textLabel.text = item;

    return c;
}

I don't understand what indexPath.row returns or what index it is representing in the array, i have just reach the part of the book where i actually get to make small applications, so i am used to just passing an integer for an index.

NSString *item = [self.tasks objectAtIndex:indexPath.row];

I don't know if all this code is needed but i just wanted to make sure you had all the code needed to answer the question.

.h file - http://pastebin.com/TRnPqn4d

.m file - http://pastebin.com/YXZffwye

like image 558
hanseN Avatar asked Feb 11 '23 01:02

hanseN


2 Answers

The indexPath you are relating to here includes two bits of information.

  1. The section - The section in the table that the cell is going to be placed into.
  2. The row - The row (in the section) that the cell will be placed into.

So to answer "What does it return?". It depends on which section/row the cell is going to go into.

The function it is in is run once for each visible row. So to start with the indexPath.row will be 0. Then it will be 1, then 2, then 3 and so on.

You do this so that you can get the correct string from the array each time.

like image 155
Fogmeister Avatar answered Feb 26 '23 19:02

Fogmeister


NSIndexPath UIKit Additions adds a category on NSIndexPath that adds section and row properties along with a few other additions.

row
An index number identifying a row in a section of a table view. (read-only)
@property(nonatomic, readonly) NSInteger row

section
An index number identifying a section in a table view or collection view. (read-only)
@property(nonatomic, readonly) NSInteger section

like image 44
zaph Avatar answered Feb 26 '23 19:02

zaph