views:

178

answers:

3

I am implementing an optional delegate method on the Cocoa Touch API. What I would like to do is, first call the method that would have been called if I didn't implement the delegate ... then make changes to the result ... then return my modified version.

Here's an example:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section; {
  /* this line: */ UIView * headerView = [someObject tableView:tableView viewForHeaderInSection:section];
  [headerView setBackgroundColor:[UIColor redColor]];
  return headerView;
}

The marked line doesn't work. I could put someObject = tableView.delegate, but that just gives me infinite recursion. Is there some trick to make the tableView do whatever it would do if the optional method weren't implemented? I'm not super hopeful, but it would be cool if possible.

+2  A: 

I'm guessing UITableView does something like this:

if ([delegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
    [delegate tableView:self viewForHeaderInSection:section];
} else {
    // Does its own thing instead
}

So I don't think it would be possible for you to get the the original one, that way.

jbrennan
+2  A: 

Check out the documentation on respondsToSelector -- it gives you the ability to test and see if an object will, well, respond to the selector :)

fbrereto
+6  A: 

There is no method that would have been called if you didn't implement the delegate. Delegates are not like subclasses; they're not a language feature. The UITableView (in this case), does some work, looks to see if its -delegate property is non-nil (which is just a random ivar that happens to be called "delegate"), if so it sees the delegate implements the delegate method, calls it if it does, then does some more work.

UITableView does not expose a default section header view (it's a private subclass called UISectionHeaderCell I believe), so Apple isn't making any promises about how it's implemented. or giving us a good way to get ahold of it There are several ways to get to the view in question, but Apple hasn't yet given us any supported way that I know of.

But to the general question about delegates, what you're asking for doesn't exist because it isn't how delegates are implemented.

Rob Napier