popToViewController inserts top view controller to the bottom

Hi all,

hope ur doing well. Recently I found a strange behavior on UINavigationController popToViewController:animated:.

I setup a dummy app with an UINavigationController and insert multiple UIViewControllers into it (no less than 4 view controllers). After that, I call [navigationController popToViewController:navigationController.viewControllers[0] animated:YES] to pop to the root view controller and monitors the status of navigationController.viewControllers instantly after it (in the same block).

What I found is that UIKit instead of just popping all view controllers on top of the previous root view controller, it also inserts the previous top view controller to the bottom of the stack. This seems like a intermediate behavior and from the UI everything looks fine.

Example:

  • Before popTo: [A, B, C, D]
  • Calling popTo: [navigationController popToViewController:navigationController.viewControllers[0] animated:YES]
  • After popTo: [D, A]

Would like to get some help to understand if this is an expected behavior and the reason. Thanks!

Answered by Frameworks Engineer in 759844022

Yes, this is expected behavior. The top most view controller needs to remain as a child view controller of UINavigationController for other reasons (such as being able to access its navigationController property and obtain a non-nil value during the viewWill/DidDisappear: callbacks).

It should still be noted that its appearance specifically in the viewControllers array is not strictly necessary, but rather a side effect of how UINavigationController is implemented. This itself may change someday.

Accepted Answer

Yes, this is expected behavior. The top most view controller needs to remain as a child view controller of UINavigationController for other reasons (such as being able to access its navigationController property and obtain a non-nil value during the viewWill/DidDisappear: callbacks).

It should still be noted that its appearance specifically in the viewControllers array is not strictly necessary, but rather a side effect of how UINavigationController is implemented. This itself may change someday.

@Rincewind Thanks a lot for the explanation! Just curious, is there any other similar cases in the UIKit stack APIs?

popToViewController inserts top view controller to the bottom
 
 
Q