View Controller 生命周期

View Controller 生命周期

  • View Controller 拥有生命周期

    即,程序运行过程中,会调用(回调)一写方法,在 apple 上也叫向对象发送消息

  • 生命周期的作用

    你可以重写相关的方法,去完成特定的工作

生命周期

开始实例化

awakeFromNib and outlets get set

Anything that would go in your Controller’s init method would have to go in awakeFromNib too (because init methods are not called on objects that come out of a storyboard).

-(void)setup{}; //do something which can’t wait until viewDidLoad
- (void)awakeFromNib { [self setup]; }
// UIViewController’s designated initializer is initWithNibName:bundle: (ugh!)
- (instancetype)initWithNibName:(NSString *)name bundle:(NSBundle *)bundle
{
    self = [super initWithNibName:name bundle:bundle];
    [self setup];
    return self;
}

viewDidLoad

- (void)viewDidLoad
{
[super viewDidLoad]; // always let super have a chance in lifecycle methods
// do some setup of my MVC
}

view的几何属性(bounds)还没有设置

此时,你不能确定现在是在 iphone5大小的屏幕 还是 ipad or???

所以不要初始化geometry-dependent的属性

可以在此处添加各种UI子控件。

viewWillLayoutSubviews: and viewDidLayoutSubviews:

(when geometry is determined)

viewWillAppear:and viewDidAppear:

(next group can happen repeatedly as your MVC appears and disappears from the screen ...)

- (void)viewWillAppear:(BOOL)animated;

View 只会 "loaded" 一次,但是可能"appear" "disappear" 很多次。

不应该把放在 viewDidLoad 中的代码放到此处。

此处应该组织一些当你的 MVC 离开屏幕时的处理

以后可以使用这个函数进行性能优化,使用这个函数(而不是 viewDidLoad)启动耗时的操作(可能在其他的线程)

view 的 geometry 在此处设置,屏幕渲染

viewWillLayoutSubviews: and viewDidLayoutSubviews:

(whenever geometry changes again while visible, e.g. device rotation)

viewWillDisappear:and viewDidDisappear:

(if it is autorotation, then you also get will/didRotateTo/From messages--rare to use these)

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated]; // call super in all the viewWill/Did... methods 
    // let’s be nice to the user and remember the scroll position they were at ...
    [self rememberScrollPosition]; // we’ll have to implement this, of course 
    // do some other clean up now that we’ve been removed from the screen
    [self saveDataToPermanentStore]; // maybe do in did instead?
    // but be careful not to do anything time-consuming here, or app will be sluggish
    // maybe even kick off a thread to do what needs doing here (again, we’ll cover threads later)
}

didReceiveMemoryWarning

This rarely happens, but well-designed code with big-ticket memory uses might anticipate it. Examples: images and sounds.
Anything “big” that can be recreated should probably be released (i.e. set strong pointer to nil).

没有“unload”之类的,到此结束。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容