SLN
SLN

Reputation: 5092

What's the data type used by navigation stacks in the navigation controller

A navigation controller object manages the currently displayed screens using the navigation stack, which is represented by an array of view controllers.

The quote and the figure are both come from the Apple official document. The quote mentioned the words navigation stack while the figure actually points NSArray to the Navigation stack.

And this description starts to make me feel confused

The first view controller in the array is the root view controller. The last view controller in the array is the view controller currently being displayed

The quote describes the characteristics which belong to the stack data type, plus, they do have the push segue existing in the StoryBoard. seems UINavigationController do use the stack data type rather than the array/NSArray data type.

Question 1

What exactly is the data structure used by the navigation stack of the navigation controller, Stack or Array?

Question 2

What is the difference between topViewController and rootViewController in navigation controller

Upvotes: 1

Views: 269

Answers (2)

Aditya Srivastava
Aditya Srivastava

Reputation: 2650

Your first Question's answer is NavigationStack uses Array Representation of Stack Data Structure. I think there are two representation of Stack, one is array and other is linked list. So push and pop operations are performed using Array here by using :-

pushViewController(_:animated:)
popViewController(animated:)

Your Second Question's Answer - TopViewController of navigation controller represents the view controller at the top of the stack and RootViewController is the first viewcontroller on the Stack

Hope this helps!.

Upvotes: 1

Reinier Melian
Reinier Melian

Reputation: 20804

Question 1 ViewControllers attribute is defined as NSArray in UINavigationController definition, but have stack behaviours like popViewController method and pushViewController method but you can also modify your ViewControllers array passing a new Array ViewControllers array

@property(nonatomic,copy) NSArray<__kindof UIViewController *>*viewControllers; // The current view controller stack.

2 Examples of Stack Behaviour Methods

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
//Others
- (nullable UIViewController *)popViewControllerAnimated:(BOOL)animated
//Others

But you can also set your ViewControllers array using this method

- (void)setViewControllers:(NSArray<UIViewController *> *)viewControllers animated:(BOOL)animated;

Question 2

TopViewController is the current viewController you're seeing and the rootViewController is the firstViewController has been added to your navigation stack

Upvotes: 1

Related Questions