继承 有时候你可能需要重载代理方法

来源:互联网 发布:玄武智慧数据科技 编辑:程序博客网 时间:2024/05/01 21:21

有时候你可能需要重载代理方法。考虑有两个 UIViewController 子类的情况:UIViewControllerA 和 UIViewControllerB,有下面的类继承关系。

UIViewControllerB < UIViewControllerA < UIViewController

UIViewControllerA 遵从 UITableViewDelegate 并且实现了 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath.

你可能会想要在 UIViewControllerB 中提供一个不同的实现,这个实现可能是这样子的:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {    CGFloat retVal = 0;    if ([super respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]) {        retVal = [super tableView:self.tableView heightForRowAtIndexPath:indexPath];    }    return retVal + 10.0f;}

但是如果超类(UIViewControllerA)没有实现这个方法呢?此时调用[super respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]方法,将使用 NSObject 的实现,在 self 上下文深入查找并且明确 self 实现了这个方法(因为 UITableViewControllerA遵从 UITableViewDelegate),但是应用将在下一行发生崩溃,并提示如下错误信息:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewControllerB tableView:heightForRowAtIndexPath:]: unrecognized selector sent to instance 0x8d82820'*** 由于未捕获异常 `NSInvalidArgumentException(无效的参数异常)`导致应用终止,理由是:向实例 ox8d82820 发送了无法识别的 selector `- [UIViewControllerB tableView:heightForRowAtIndexPath:]`
0 0
原创粉丝点击