When should I call the parent version of a function? Should it be the first thing in the child function or the last thing? (And by "parent" and "child", I mean the inheritance hierarchy, not the view hierarchy.)
This question can be answered in general, but I personally came across it when implementing view controller functions in iOS. So answers specific to iOS View Controllers programming are also relevant here.
For example:
class ChildViewController: ParentViewController {
override func viewDidLoad() {
// option 1 to do function's job
super.viewDidLoad()
// option 2 to do function's job
}
}
I always thought option 1 was better (no reason, just a feeling!), but recently, I was writing some code which made me choose option 2.
Thanks in advance.
Edit:
In my case, two child classes inherit from a single parent class. Both children have a UIBarButton which should be disabled when view loads. I wanted to put the disabling code in parent view controller (because it's the exact line of code for both self.navigationItem.rightBarButtonItem?.enabled = true) but the buttons are different so I have to create the buttons at each child view controller. This way, I have to call parent's viewDidLoad() after creating the button.
Should I change my code (and copy that line of code) or my approach is correct?
As far as viewDidLoad and similar methods are concerned you should make call to super implementation at the very beginning of the method because you want to have everything already setup before your own code starts working
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With