Strange Behavior of UITabBarController selectedIndex and UINavigationController pop

                UITabBarController
                         |
                         |
    VC_Tab1 --------------------------- VC_Tab2
        |                                  |
        |                                  |
  VC_Tab1_Child                      VC_Tab2_Child
        |
   (HeaderView)
        |
    (MyButton)

The structure of the view controllers and views in the project is as described above.

<case 1>
self.navigationController?.popToRootViewController(animated: false)
        
tabBarController.selectedIndex = 1

When popToRootViewController(animated: false) is called in VC_Tab1_Child, followed by setting the tab controller’s selectedIndex = 1, the following results are observed:

viewWillAppear(_:), <VC_Tab2_Child>
deinit, <VC_Tab1_Child>
viewDidAppear(_:), <VC_Tab2_Child>

The originally expected results are as follows

viewWillDisappear(_:), <VC_Tab1_Child>
viewDidDisappear(_:), <VC_Tab1_Child>
deinit, <VC_Tab1_Child>
deinit, <HeaderView>
deinit, <MyButton>
headerView.backButton.rx.tap -> Event completed
headerView.backButton.rx.tap -> isDisposed
viewWillAppear(_:), <VC_Tab2_Child>
viewDidAppear(_:), <VC_Tab2_Child>

The HeaderView belonging to VC_Tab1_Child was not deallocated, and the resources associated with that view were also not released. Similarly, VC_Tab1_Child.viewWillDisappear and VC_Tab1_Child.didDisappear were not called.

<case 2>
self.navigationController?.popToRootViewController(animated: false)
        
DispatchQueue.main.async {
     tabBarController.selectedIndex = 1
}

After performing the pop operation as shown in the code and waiting for a short period before testing, the expected results were generally achieved. (However, rarely, the results were similar to those observed when called without async.)”

<case 3>
self.navigationController?.popToRootViewController(animated: false)
        
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    tabBarController.selectedIndex = 1
}

When a sufficient delay was ensured as described above, the expected results were achieved 100% of the time.”

The abnormal behavior is more pronounced in iOS versions prior to 18 and varies depending on the iOS version.

I couldn’t find any documentation explaining the unexpected behavior shown in the results above. What could be the cause? The simulation code is provided below.

https://github.com/linusix/UITabBarController_Test2

Strange Behavior of UITabBarController selectedIndex and UINavigationController pop
 
 
Q