iOS开发学习笔记(OC语言)——UIView和UIViewController生命周期

Posted 观海云不远

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS开发学习笔记(OC语言)——UIView和UIViewController生命周期相关的知识,希望对你有一定的参考价值。

UIView 生命周期


#import "ViewController.h"

@interface TestView: UIView

@end

@implementation TestView

- (instancetype)init
    self = [super init];
    if (self) 
        
    
    return self;


- (void)willMoveToSuperview:(nullable UIView *)newSuperview 
    [super willMoveToSuperview:newSuperview];


- (void)didMoveToSuperview 
    [super didMoveToSuperview];


- (void)willMoveToWindow:(nullable UIWindow *)newWindow 
    [super willMoveToWindow:newWindow];


- (void)didMoveToWindow 
    [super didMoveToWindow];


@end


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad 
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    TestView *view = [[TestView alloc] init];
    view.backgroundColor = [UIColor redColor];
    view.frame = CGRectMake(100, 100, 100, 100);
    [self.view addSubview:view];


@end

通过断点调试,可以发现生命周期是:

  1. init
  2. willMoveToSuperview
  3. didMoveToSuperview
  4. willMoveToWindow
  5. didMoveToWindow

UIViewController 生命周期

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (instancetype)init 
    self = [super init];
    if (self) 
        
    
    return self;


- (void)viewWillAppear:(BOOL)animated 
    [super viewWillAppear:animated];


- (void)viewDidAppear:(BOOL)animated 
    [super viewDidAppear:animated];


- (void)viewDidLoad 
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor redColor];
    view.frame = CGRectMake(100, 100, 100, 100);
    [self.view addSubview:view];


- (void)viewWillDisappear:(BOOL)animated 
    [super viewWillDisappear:animated];


- (void)viewDidDisappear:(BOOL)animated 
    [super viewDidDisappear:animated];



@end

通过断点调试,可以发现生命周期是:

  1. init
  2. viewDidLoad
  3. viewDidAppear

如果移除,顺序是:

  1. viewWillDisappear
  2. viewDidDisappear

以上是关于iOS开发学习笔记(OC语言)——UIView和UIViewController生命周期的主要内容,如果未能解决你的问题,请参考以下文章

iOS开发入门 ? OC语言·笔记四

ios开发之OC基础-类和对象

OC笔记一:Objective

iOS开发入门 ? OC语言·笔记五

OC学习小结之ios运行过程详解

Objective-C学习笔记