I often call a web service when a view loads and save an NSMutableArray with the contents of the call. Then in cellForRowAtIndexPath I retrieve the rows from this array. I use what feels like a hack to get the row index from the indexPath, however:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
<snip cell alloc stuff>
// Configure the cell.
unsigned int *indexes = (unsigned int*)calloc( [indexPath length], sizeof( unsigned int ) );
[indexPath getIndexes:indexes];
Tasks *task = [_tasksArray objectAtIndex:indexes[1]];
free( indexes );
cell.textLabel.text = [task getname];
cell.detailTextLabel.text = [NSString stringWithFormat:@"Started: %@", [task getstarted] ? [[task getstarted] description] : @"Not Yet"];
return cell;
}
Is there a better way to do this?
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.
add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.
Index paths describe an item's position inside a table view or collection view, storing both its section and its position inside that section. For example, the first row in a table would have section 0, row 0, whereas the eighth row in the fourth section would have section 3, row 7.
Thus the two are functionally identical. In terms of programming style – and perhaps the definition chain – you would be better using "row" in the context of tables, and "item" in the context of collections. The core interface of NSIndexPath is defined in NSIndexPath. h.
Try to access the row part of the indexPath
indexPath.row
Here's a link to Apple's documentation for NSIndexPath.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With