IOS UIView的生命周期的实例详解
任何对象的者有一个生命周期,即都存在一个实例化到销毁的过程。
UIView对象也不例外,那么UIView从init/new开始后,直到dealloc结束的过程中都经历了哪些过程呢?
首先自定义继承自UIView的对象LifeView
#import <UIKit/UIKit.h>
@interface LifeView : UIView
@end
#import "LifeView.h"
@interface LifeView ()
{
NSInteger count;
}
@end
@implementation LifeView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
NSLog(@"<-- 1 %s , count = %@-->", __func__, @(count++));
}
return self;
}
- (void)willMoveToSuperview:(nullable UIView *)newSuperview
{
NSLog(@"<-- 2 %s , count = %@-->", __func__, @(count++));
}
- (void)didMoveToSuperview
{
NSLog(@"<-- 3 %s , count = %@-->", __func__, @(count++));
}
- (void)willMoveToWindow:(nullable UIWindow *)newWindow
{
NSLog(@"<-- 4/7 %s , count = %@-->", __func__, @(count++));
}
- (void)didMoveToWindow
{
NSLog(@"<-- 5/8 %s , count = %@-->", __func__, @(count++));
}
- (void)layoutSubviews
{
NSLog(@"<-- 6 %s , count = %@-->", __func__, @(count++));
}
- (void)removeFromSuperview
{
NSLog(@"<-- 9 %s , count = %@-->", __func__, @(count++));
}
- (void)dealloc
{
NSLog(@"<-- 10 %s , count = %@-->", __func__, @(count++));
}
@end
其次,在B视图控制器中实例化,并添加到父视图
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"life view";
LifeView *lifeView = [[LifeView alloc] initWithFrame:CGRectMake(10.0, 80.0, 100.0, 100.0)];
[self.view addSubview:lifeView];
lifeView.tag = 1000;
lifeView.backgroundColor = [UIColor orangeColor];
}
当B视图控制器被push,或present出来时,被调用的LifeView的相关方法,如下所示:
// 实例化时
2017-06-16 00:37:10.694 DemoViewLife[3963:121184] <-- 1 -[LifeView initWithFrame:] , count = 0-->
2017-06-16 00:37:10.695 DemoViewLife[3963:121184] <-- 2 -[LifeView willMoveToSuperview:] , count = 1-->
2017-06-16 00:37:10.695 DemoViewLife[3963:121184] <-- 3 -[LifeView didMoveToSuperview] , count = 2-->
2017-06-16 00:37:10.697 DemoViewLife[3963:121184] <-- 4/7 -[LifeView willMoveToWindow:] , count = 3-->
2017-06-16 00:37:10.697 DemoViewLife[3963:121184] <-- 5/8 -[LifeView didMoveToWindow] , count = 4-->
2017-06-16 00:37:10.701 DemoViewLife[3963:121184] <-- 6 -[LifeView layoutSubviews] , count = 5-->
当B视图控制器被pop,或dismiss时,被调用的LifeView的相关方法,如下所示:










