一、介绍

UIViewController是iOS开发中的核心控件,没有它那基本上任何功能都无法实现,虽然系统已经做了所有控件的生命维护,但是,了解它的生命周期是如何管理还是非常有必要的。网上有很多教程,别人写的始终是别人的,自己动手实践一下,理解才能更深刻,本文就来捋一遍VC的生命周期。

 

二、思路

通过三个VC,第1个VC是storyBoard创建的,第2个VC是纯code创建的,第3个是xib创建的。分别称为BoardInitViewController、CodeInitViewController、XibInitViewController,这三个控制器采用导航模式进行交互,现在在VC中把所有跟初始化相关的方法都实现一下并做打印,如下:

iOS:从头捋一遍VC的生命周期

BoardInitViewController:

//
//  BoardInitViewController.m
//  声明周期
//
//  Created by 夏远全 on 2019/11/3.
//  Copyright © 2019 Beijing Huayue Education Technology Co., Ltd. All rights reserved.
//

#import "BoardInitViewController.h"
#import "CodeInitViewController.h"

@interface BoardInitViewController ()

@end

@implementation BoardInitViewController

+(void)load {
    [super load];
    NSLog(@"boardVc---------%s",__func__);
}

+(void)initialize {
    [super initialize];
    NSLog(@"boardVc---------%s",__func__);
}

+(instancetype)alloc {
    NSLog(@"boardVc---------%s",__func__);
    return [super alloc];
}

- (nullable instancetype)initWithCoder:(NSCoder *)coder {
    NSLog(@"boardVc---------%s",__func__);
    return [super initWithCoder:coder];
}

- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil {
    NSLog(@"boardVc---------%s",__func__);
    return [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
}

-(instancetype)init {
    NSLog(@"boardVc---------%s",__func__);
    return [super init];
}

- (void)loadView {
    [super loadView];
    NSLog(@"boardVc---------%s",__func__);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor greenColor];
    self.title = @"boardVc";
    NSLog(@"boardVc---------%s",__func__);
}

- (void)viewWillAppear:(BOOL)animated  {
    [super viewWillAppear:animated];
    NSLog(@"boardVc---------%s",__func__);
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"boardVc---------%s",__func__);
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    NSLog(@"boardVc---------%s",__func__);
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    NSLog(@"boardVc---------%s",__func__);
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    NSLog(@"boardVc---------%s",__func__);
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    NSLog(@"boardVc---------%s",__func__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"boardVc---------%s",__func__);
}

-(void)dealloc {
    NSLog(@"boardVc---------%s",__func__);
}



-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    CodeInitViewController *codeVc = [[CodeInitViewController alloc] init];
    [self.navigationController pushViewController:codeVc animated:YES];
}

@end
View Code

相关文章: