iOS 深入理解UINavigationController 和 UIViewController 之间的关系

时间:2023-11-25 21:23:32

创建三个类

  1. BasicViewController : UIViewController
  2. SecondViewController : UIViewController
  3. ThirdViewController : UIViewController

然后我们在BasicViewController .m文件中push一个viewController: 
SecondViewController *svc = [SecondViewController new]; 
[self.navigationController pushViewController:svc animated:true]; 
在SecondViewController.m文件中pop出viewController: 
[self.navigationController popViewControllerAnimated:true]

问题就来了, 
push和pop是同一个viewController,那为什么用self.navigationController 就可以知道了

其中在AppDelegate.m:

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2. {
  3. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  4. // Override point for customization after application launch.
  5. BasicViewController  *basicViewController = [BasicViewController new];//实例化内存后,_parentViewController-->nil
  6. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:basicViewController];
  7. // self.window.rootViewController = basicViewController.parentViewController;
  8. self.window.rootViewController = navigationController;
  9. [self.window makeKeyAndVisible];
  10. return YES;
  11. }

等价于

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2. {
  3. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  4. // Override point for customization after application launch.
  5. BasicViewController  *basicViewController = [BasicViewController new];//实例化内存后,_parentViewController-->nil
  6. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:basicViewController];
  7. self.window.rootViewController = basicViewController.parentViewController; //不可以注释上一句,因为上一句是为_parentViewController实例化
  8. // self.window.rootViewController = navigationController;
  9. [self.window makeKeyAndVisible];
  10. return YES;
  11. }

分配内存如图 
iOS 深入理解UINavigationController 和 UIViewController 之间的关系