To address those who say "this is a bad idea", in my case, my need for this is that I have a button on my UITableViewCell
that, when pressed, is a segue to another view. Since this is not a selection on the cell itself, [self.tableView indexPathForSelectedRow]
does not work.
This leaves me two options:
- Store the object that I need to pass into the view in the table cell itself. While this would work, it would defeat the point of me having an
NSFetchedResultsController
because I do not want to store all the objects in memory, especially if the table is long.
- Retrieve the item from the fetch controller using the index path. Yes, it seems ugly that I have to go figure out the
NSIndexPath
by a hack, but it's ultimately less expensive than storing objects in memory.
indexPathForCell:
is the correct method to use, but here's how I would do it (this code is assumed to be implemented in a subclass of UITableViewCell
:
// uses the indexPathForCell to return the indexPath for itself
- (NSIndexPath *)getIndexPath {
return [[self getTableView] indexPathForCell:self];
}
// retrieve the table view from self
- (UITableView *)getTableView {
// get the superview of this class, note the camel-case V to differentiate
// from the class' superview property.
UIView *superView = self.superview;
/*
check to see that *superView != nil* (if it is then we've walked up the
entire chain of views without finding a UITableView object) and whether
the superView is a UITableView.
*/
while (superView && ![superView isKindOfClass:[UITableView class]]) {
superView = superView.superview;
}
// if superView != nil, then it means we found the UITableView that contains
// the cell.
if (superView) {
// cast the object and return
return (UITableView *)superView;
}
// we did not find any UITableView
return nil;
}
P.S. My real code does access all this from the table view, but I'm giving an example of why someone might want to do something like this in the table cell directly.