Why is the UITabBarControllerDelegate nil right af

2019-07-09 02:37发布

I have a weird issue involving UITabBarControllerDelegate.

I am using the following code:

import UIKit

class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = MainTabBarControllerDelegate()
        print("did set delegate to \(self.delegate)")
    }

}

class MainTabBarControllerDelegate: NSObject, UITabBarControllerDelegate {

    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
        print("selected: \(viewController) --> index: \(tabBarController.selectedIndex)")
    }

}

Then, in my Storyboard I have the vanilla UITabBarController with two plain UIViewControllers connected to it. I simply want to catch the tab change events, but for some reason the delegate of my MainTabBarController doesn't get set properly.

When I run the project with the code from above, the console outputs:

did set delegate to nil

Why doesn't it create a proper instance of MainTabBarControllerDelegate so that its delegate methods can be called?

1条回答
萌系小妹纸
2楼-- · 2019-07-09 02:52

Here self.delegate = MainTabBarControllerDelegate() you create a delegate and immediately assign it to the delegate property, which is weak. So the delegate gets created but then immediately disposed because there is nothing that holds a strong reference to it.

查看更多
登录 后发表回答