I’m reading through the Big Nerd Ranch iOS guide and I have a question about this piece of code here:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
}
BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[p description]];
return cell;
}
BNRItemStore is just a data store object and I’ve already added five BNRItem objects to it in the initializer method. Their string descriptions are then printed to the UI. My confusion specifically is about this line here:
BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
The way I understand this line is that objectAtIndex: just retrieves the items in the BNRItemStore and assigns them to the variable. The question I have is this:
How is objectAtIndex: able to return all five objects to the variable *p with the argument [indexPath row]? I was under the impression that an indexPath object holds a single section and a single row. So the row property would just return a single row index. Here it looks like the array is being looped through and its 5 contents returned to the variable, which are then printed to the UI. Or is that not what’s going on? What is the row property actually doing here?
Your understanding is correct. NSIndexPath encapsulates a section and a row. I think your confusion is that
BNRItem *pis not pointing to all 5 items (it’s only pointing to one at a time)… rather, the methodtableView:cellForRowAtIndexPath:is called for each row that is being displayed in the Table View.There is another method,
tableView:numberOfRowsInSection:which is called. I assume this method is returning the number 5, sotableView:cellForRowAtIndexPath:is called 5 times… each time the indexPath will have a different row, and thus print a different object.