iOS-UIViewController生命周期

UIViewController的生命周期比较简单,整个流程调用代码顺序如下:

  1. initWithNibName:bundle: 初始化UIViewController,执行关键数据初始化操作,非StoryBoard创建UIViewController都会调用这个方法.

  2. initWithCoder: 如果通过StoryBoard进行视图管理,程序不会直接初始化一个UIViewController,StoryBoard会自动初始化或在segue被触发时自动初始化,因此方法initWithNibName:bundle不会被调用,但是initWithCoder会被调用。

  3. loadView :当访问UIViewController的View属性时,View如果此时为nil,那么ViewController会自动调用loadView方法来初始化一个UIView并赋值给UIViewController的View;如果没有重载lodaView方法,则UIViewController会从nib或StoryBoard中查找默认的loadView,默认的loadView会返回一个空白的UIView对象.

  4. viewDidLoad:当loadView将view载入内存中,可以对加载网络数据,视图的UI初始化.

  5. viewWillAppear:系统在载入所有的数据后,在视图展示之前还可以进行进一步的调整(比如设置状态栏方向).

  6. viewWillLayoutSubviews:view 即将布局其Subviews.

  7. viewDidLayoutSubviews:view已经布局其Subviews.

  8. viewDidAppear:视图完全展示在界面之前最后的调整.

  9. viewWillDisappear:在视图切换是,当前视图在即将被移除、或被覆盖是,此时还没有调用removeFromSuperview。

  10. viewDidDisappear:view已经消失或被覆盖,此时已经调用removeFromSuperView;

  11. dealloc:视图被销毁.

  12. didReceiveMemoryWarning:在内存足够的情况下,app的视图通常会一直保存在内存中,但是如果内存不够,一些没有正在显示的viewController就会收到内存不够的警告,然后就会释放自己拥有的视图,以达到释放内存的目的。但是系统只会释放内存,并不会释放对象的所有权,所以通常我们需要在这里将不需要显示在内存中保留的对象释放它的所有权,将其指针置nil。

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        NSLog(@"FlyElephant---%s", __FUNCTION__);
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    NSLog(@"FlyElephant---%s", __FUNCTION__);
    if (self = [super initWithCoder:aDecoder]) {
        NSLog(@"FlyElephant---%s", __FUNCTION__);
    }
    return self;
}

- (void)loadView {
    [super loadView];
    NSLog(@"FlyElephant---%s", __FUNCTION__);
    self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view.backgroundColor = [UIColor greenColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"FlyElephant--%s", __FUNCTION__);
}

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

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

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

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

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

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

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

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

非StoryBoard中控制器加载过程:


FlyElephant.png

StoryBoard中控制器加载过程:


FlyElephant.png

推荐阅读更多精彩内容