有时候你可能需要重载代理方法。考虑有两个 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:]`
本文探讨了在SwiftUI中如何正确地重载代理方法,特别是在子类中提供不同于父类的方法实现。当父类未实现某个代理方法时,直接调用会引发应用崩溃的问题,并给出了解决方案。
1084

被折叠的 条评论
为什么被折叠?



