Using the same property name/reference for Outlets

2019-09-14 06:04发布

问题:

So I have a base class UIViewController called UITabBarTopLevelViewController:

class UITabBarTopLevelViewController: UIViewController {

@IBOutlet weak var uiNavItemTitle: UINavigationItem!

override func viewDidLoad() {
    super.viewDidLoad()
    uiNavItemTitle.titleView = CoreUtility.LogoForUINavBarGet()
    // Do any additional setup after loading the view.
}

I then have two UIViewControllers that inherit from my base class and both look like this, except the second is called MyViewController2:

class MyViewController1: UITabBarTopLevelViewController {

//@IBOutlet weak var uiNavItemTitle: UINavigationItem!

override func viewDidLoad() {
    super.viewDidLoad()
    //uiNavItemTitle.titleView = CoreUtility.LogoForUINavBarGet()

}

I add a Navigation Bar object to each child UIViewController super view and then I CTRL drag and add a new outlet to each UIViewController child class:

And here is the second CTRL drag outlet:

These are different references, but I can comment out the @IBOutlet weak var uiNavItemTitle: UINavigationItem! in my child classes and reference one time only in the base class UITabBarTopLevelViewController, for both MyViewController1 and MyViewController2.

You can see, when I hover over the outlet circle, in my base class, it highlights both UINavigationItem in the Story Board:

I am surprised this works, its nice for me that it works because I only need to set the uiNavItemTitle.titleView for my logo one time for both views. This is what I want but there seems to be a bit of magic that I can reference multiple outlet references one time in my base class and there is no bugs or crashes.

I currently have no memory leaks or crashes and my app is working just fine and doing exactly as I desire.

Will there be any bugs with this?

Could someone explain how this is working?

Is the fact that this works, not surprising to experienced Swift developers?

回答1:

That's how subclass exactly works.

You placed a UINavigationItem in the base class UITabBarTopLevelViewController through

uiNavItemTitle.titleView = CoreUtility.LogoForUINavBarGet()

Also, MyViewController1 and MyViewController2 inherit from the base class UITabBarTopLevelViewController. That's say these child viewControllers both have a UINavigationItem which inherit from their UITabBarTopLevelViewController.

This is not a bug, on the other hand, more like a topic about design pattern though. You could place all the base stuff into a base class, inherit from those classes and implement the specific detail within the child class.

HTH.