Monotouch: The correct way to override UIViewController method
Suppose I have a custom controller called MyCustomUIViewController that extends UIViewController:
public class MyCustomUIViewController : UIViewController
{
//- my class implementation
}
Now I want to ove开发者_如何学Crride a method like this:
public override void ViewDidLoad()
{
base.ViewDidLoad();
//- other stuff here
}
Is it necessary to call base.ViewDidLoad() or not? Where do I have to call base methods? Before or after custom code (i.e. other stuff here)? I've seen many samples where base methods are put after doing stuff or even omitted.
Thank you in advance. Regards.
Yes, when you override you need to call base. Calling base ensures your not short-circuiting what apple may have now or in the future. In addition, it's a good habit because in deeper inheritance, you can also short-circuit some code that needs to get called.
Typically, you call base first.
For example, it's the equivalent if this typical objective-c code:
- (void)viewDidLoad
{
[super viewDidLoad];
[[self navigationItem] setTitle:@"Title"];
// ...
The default implementation of ViewDidLoad is empty so it does not matter if you make the base.ViewDidLoad() call to begin with, let alone where you place the call, should you chose to make it.
One reason to insert a reference to the base implementation would be to ensure that your code still works properly, should Apple re-design viewDidLoad in such a way that it does perform some operations. In this case, i think you'd be better of placing the call at the beginning of your ViewDidLoad implementation, but it's highly unlikely for something like this to happen.
精彩评论