美文网首页
关于UIViewController生命周期

关于UIViewController生命周期

作者: Sniper_Zheng | 来源:发表于2016-02-26 13:49 被阅读305次

    最近稍微有了点时间,充实一下自己,恶补了一下基础.
    关于UIViewController,我看了一些其他人的博客,在根据自己的理解,总结了一下。


    ViewControllerLife.png

    UIViewController 生命周期

    1.通过alloc init 分配内存,初始化controller.

    2.loadView
    loadView方法默认实现[super loadView]
    如果在初始化controller时指定了xib文件名,就会根据传入的xib文件名加载对应的xib文件,如果没传xib文件名,默认会加载跟controller同名的xib文件,如果没找到相关联的xib文件,就会创建一个空白的UIView,然后赋給controller的view

    3.viewDidLoad
    当loadView创建完view之后会调用viewDidLoad方法
    一般我会在这里做界面上的初始化操作,比如添加按钮,子视图,等等.
    4.viewWillAppear
    当view在load完之后,将要显示在屏幕之前会调用这个方法
    在重写这些方法时候最好先调用一下系统的方法之后在做操作。比如:

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
     
        // custom code...
    }
    

    stackoverflow上的答案


    stackOverFlowAnswerViewController.png

    5.viewDidAppear
    当view已经在屏幕上显示出来之后,会调用这个方法

    当一个视图被移除屏幕并且销毁的时候

    1.viewWillDisappear
    当视图将要从屏幕上移除时候调用
    2.viewDidDisappear
    当视图已经从屏幕上移除时候调用
    3.dealloc
    view被销毁时候调用,如果是手动管理内存的话,需要释放掉之前在init和viewDidLoad中分配的内存(类似alloc,new,copy)
    dealloc方法不能由我们主动调用,必须等引用计数为0时候由系统调用.

    关于viewDidUnload
    在网上看了好多文章 总结下:
    iOS设备的内存是有限的,如果应用程序占用的内存过多的话,系统就会对应用程序发出内存警告didReceiveMemoryWarning. 并且调用viewDidUnload方法.如果controller.view不在应用程序的视图层次结构(View Hierarchy)中,也就是本视图不是当前屏幕上正在显示的视图时,就会将view释放(先释放所有子视图再释放自己,在这里系统只是释放内存,并没有释放对象的所有权,所以通常我们需要在这里讲不需要在内存中保留的对象释放所有权,也就是指针置为nil) 等本视图再次显示在屏幕上时,会再次调用viewDidLoad方法。
    但是:重要的一点!!!!

    viewDidUnload 在6.0之后已经废弃了。
    简单来说,对于iOS6,你不需要做任何以前viewDidUnload的事情,更不需要把以前viewDidUnload的代码移动到 didReceiveMemoryWarning方法中。
    引用WWDC 2012 中的一段话来给viewDidUnload说再见:
    The method viewWillUnload and viewDidUnload. We’re not going to call them anymore. I mean, there’s kind of a cost-benifit equation and analysis that we went through. In the early days, there was a real performance need for us to ensure that on memory warnings we unloaded views. There was all kinds of graphics and backing stores and so forth that would also get unloaded. We now unload those independently of the view, so it isn’t that big of a deal for us for those to be unloaded, and there were so many bugs where there would be pointers into。

    相关文章

      网友评论

          本文标题:关于UIViewController生命周期

          本文链接:https://www.haomeiwen.com/subject/jthwkttx.html