Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

ios - When a subclass overrides a method, how can we ensure at compile time that the superclass's method implementation is called?

The classic example is:

- (void)viewDidLoad {
    [super viewDidLoad]; // Subclasses sometimes forget this line

    // Subclass's implementation goes here
}

What are some ways to ensure at compile time that UIViewController subclasses always call [super viewDidLoad] when they override [UIViewController viewDidLoad]?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If we're talking about custom classes, you can add the following to your superclass's method declaration:

__attribute__((objc_requires_super));

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

And then just subclass BaseViewController throughout your project, rather than subclassing UIViewController.

Any subclass of BaseViewController which implements viewDidLoad and does not call [super viewDidLoad]; (which in turn calls UIViewController's viewDidLoad) will throw a warning.


EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...