问题描述
经典的例子是:
- (void)viewDidLoad {
[super viewDidLoad]; // Subclasses sometimes forget this line
// Subclass's implementation goes here
}
有什么方法可以确保在编译时 UIViewController
子类总是调用 [super viewDidLoad]
时他们覆盖 [UIViewController viewDidLoad]
?
What are some ways to ensure at compile time that UIViewController
subclasses always call [super viewDidLoad]
when they override [UIViewController viewDidLoad]
?
推荐答案
如果我们在说话关于自定义类,您可以将以下内容添加到超类的方法声明中:
If we're talking about custom classes, you can add the following to your superclass's method declaration:
__attribute__((objc_requires_super));
如果你想确保所有的 UIViewController
子类调用类似 [super viewDidLoad];
的方法,你可以继承 UIViewController
类似这样的事情:
And if you want to ensure that all of your UIViewController
subclasses call a method like [super viewDidLoad];
, you could subclass UIViewController
something like this:
@interface BaseViewController : UIViewController
- (void)viewDidLoad __attribute__((objc_requires_super));
// per Scott's excellent comment:
- (void)viewWillAppear:(BOOL)animated NS_REQUIRES_SUPER;
@end
@implementation BaseViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
@end
然后只是子类 BaseViewController
整个项目,而不是继承 UIViewController
。
And then just subclass BaseViewController
throughout your project, rather than subclassing UIViewController
.
任何实现 viewDidLoad
的 BaseViewController
的子类,并且不调用 [super viewDidLoad];
(反过来调用 UIViewController
的 viewDidLoad
)会发出警告。
Any subclass of BaseViewController
which implements viewDidLoad
and does not call [super viewDidLoad];
(which in turn calls UIViewController
's viewDidLoad
) will throw a warning.
编辑:我已经编辑了答案,包括 NS_REQUIRES_SUPER
的示例,每个斯科特的出色评论。这两个示例( viewDidLoad
和 viewWillAppear:
)在功能上是等效的。虽然我想象 NS_REQUIRES_SUPER
可能会为你自动完成。我将来可能会开始使用这个宏。
I've edited the answer to include an example of NS_REQUIRES_SUPER
, per Scott's excellent comment. The two examples (viewDidLoad
and viewWillAppear:
) are functionally equivalent. Though I imagine NS_REQUIRES_SUPER
probably will autocomplete for you. I'll likely begin using this macro myself in the future.
这篇关于当子类重写方法时,我们如何在编译时确保调用超类的方法实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!