iOS program execution sequence and Uiviewcontroller life cycle (grooming)

Source: Internet
Author: User

Description: This article is your own summary note, the main reference: iOS program start execution sequence appdelegate and Uiviewcontroller
life cycle UIView life cycle

A court of words and leaves. jpeg I. Boot execution sequence for iOS programs

Program start sequence diagram


iOS boot schematic. png

Specific implementation process

    1. Program entry
      Enter main function to set AppDelegate the proxy called function

    2. The program finishes loading
      [AppDelegate application:didFinishLaunchingWithOptions:]

    3. Create window window

    4. Program is activated
      [AppDelegate applicationDidBecomeActive:]

    5. When clicked command+H (for simulator, the phone is when clicked home键 )
      Program Deactivation Status
      [AppDelegate applicationWillResignActive:];
      program into the background
      [AppDelegate applicationDidEnterBackground:];

    6. Click to enter Project
      Procedures to enter the foreground
      [AppDelegate applicationWillEnterForeground:]
      Program is activated
      [AppDelegate applicationDidBecomeActive:];

Analysis

1. For applicationWillResignActive(非活动) the applicationDidEnterBackground(后台) difference between the two.

    • applicationWillResignActive(非活动):
      For example, when a call comes in or a message comes in or a lock screen, and so on, then the application hangs into the inactive state, that is, the mobile phone interface or display your current application window, but the other task is forced to occupy, it may be coming into the background state (because to enter the inactive state and then enter the background state)

    • applicationDidEnterBackground(后台):
      Refers to the current window is not your app, most of the program into the background will stay in this state for a while, time will enter after 挂起状态(Suspended) . If you have a program that can be used for a long time in the background, you can run it.
      Suspended (挂起) : The program cannot execute code in the background. The system automatically turns the program into this state and does not give notice. When suspended, the program is still in memory, when the system memory is low, the system will remove the suspended program, to provide more memory for the foreground program.

As shown in the following:


Active and inactive. png

2. UIApplicationMain function Explanation:

Entry function:

int main(int argc, char * argv[]) {        @autoreleasepool {            return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));        } } UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
    • argc and argv parameters are for consistency with the C language.

    • principalclassname (main class name) and delegateclassname (delegate class name) .
      (1) If principalclassname is nil, then its value will be obtained from info.plist , if info.plist is not, The default is uiapplication . The Principalclass class does nothing except manage the entire program's life cycle, and it only listens for events and then gives it to Delegateclass .
      (2) Delegateclass instantiates an object when the project is new. Nsstringfromclass ([Appdelegate class])

    • appdelegate class implementation file

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    NSLog(@"--- %s ---",__func__);//__func__打印方法名    return YES;}- (void)applicationWillResignActive:(UIApplication *)application {     NSLog(@"--- %s ---",__func__);}- (void)applicationDidEnterBackground:(UIApplication *)application {   NSLog(@"--- %s ---",__func__);}- (void)applicationWillEnterForeground:(UIApplication *)application {   NSLog(@"--- %s ---",__func__);}- (void)applicationDidBecomeActive:(UIApplication *)application {  NSLog(@"--- %s ---",__func__);}- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {     NSLog(@"--- %s ---",__func__);}- (void)applicationWillTerminate:(UIApplication *)application {    NSLog(@"--- %s ---",__func__);}

Print call Order
Start the program

 --- -[AppDelegate application:didFinishLaunchingWithOptions:] --- --- -[AppDelegate applicationDidBecomeActive:] ---

Press the Command + H + SHIFT

--- -[AppDelegate applicationWillResignActive:] ------ -[AppDelegate applicationDidEnterBackground:] ---

Re-click to enter the program

--- -[AppDelegate applicationWillEnterForeground:] ------ -[AppDelegate applicationDidBecomeActive:] ---

Select the emulator'sSimulate Memory Warning

--- -[AppDelegate applicationDidReceiveMemoryWarning:] ---

Analysis:

1. application:didFinishLaunchingWithOptions :
The program is executed at startup for the first time, typically creating a Window object in this function that renders the program content to the user through window.

    1. applicationWillResignActive(非活动)
      The program is going to lose Active state when called, such as have 电话 come in or press Home键 , then the program into the background state, the corresponding applicationWillEnterForeground(即将进入前台) method.

      The function mainly performs the following actions:
      A. Pausing a task that is being performed
      B. No timer
      C. reduced OpenGL ES frame rate
      D. If the game should be paused

3.applicationDidEnterBackground(已经进入后台)
CorrespondingapplicationDidBecomeActive(已经变成前台)

This method is used to:
A. Releasing a shared resource
B. Save user data (write to hard disk)
C. void Timer
D. Save enough program status for the next repair;

    1. applicationWillEnterForeground(即将进入前台)
      When the program is about to enter the foreground, call, correspond applicationWillResignActive(即将进入后台) ,
      This method is used to: Undo the applicationWillResignActive changes made.

    2. applicationDidBecomeActive(已经进入前台)
      Called when the program has changed Active(前台) . Corresponding applicationDidEnterBackground(已经进入后台) .
      Note: If the program is in the background, refresh the user interface in this method

    3. applicationWillTerminate
      Called when the program is about to exit. Remember to save the data as a applicationDidEnterBackground method.


Wait. JPEG two. UIViewControllerThe life cycle

code example

#pragma Mark---Life circle//non-storyboard (xib or non-xib) go this way-(instancetype) Initwithnibname: (NSString *) Nibnameornil    Bundle: (NSBundle *) Nibbundleornil {NSLog (@ "%s", __function__); if (self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil]) {} return to self;}    If the concatenation diagram is connected storyboard go this way-(instancetype) Initwithcoder: (Nscoder *) Adecoder {NSLog (@ "%s", __function__); if (self = [Super Initwithcoder:adecoder]) {} return to self;}     Xib loading Complete-(void) awakefromnib {[Super awakefromnib]; NSLog (@ "%s", __function__);}    Load view (default from NIB)-(void) Loadview {NSLog (@ "%s", __function__);    Self.view = [[UIView alloc] Initwithframe:[uiscreen mainscreen].bounds]; Self.view.backgroundColor = [Uicolor redcolor];}    The view controller in the view load is complete, Viewcontroller comes with the view load complete-(void) Viewdidload {NSLog (@ "%s", __function__); [Super Viewdidload];}    The view will appear-(void) Viewwillappear: (BOOL) Animated {NSLog (@ "%s", __function__); [Super viewwillappear:animated];} View is about to layout its subviews-(void) Viewwilllayoutsubviews {NSLog (@ "%s", __function__); [Super Viewwilllayoutsubviews];}    View has been layout its subviews-(void) viewdidlayoutsubviews {NSLog (@ "%s", __function__); [Super Viewdidlayoutsubviews];}    View already appears-(void) Viewdidappear: (BOOL) Animated {NSLog (@ "%s", __function__); [Super viewdidappear:animated];}    The view is going to disappear-(void) Viewwilldisappear: (BOOL) Animated {NSLog (@ "%s", __function__); [Super viewwilldisappear:animated];}    The view has disappeared-(void) Viewdiddisappear: (BOOL) Animated {NSLog (@ "%s", __function__); [Super viewdiddisappear:animated];} Memory warning//Analog memory Warning: Click Emulator->hardware-> Simulate Memory warning-(void) didreceivememorywarning {NSLog (@ "%s", __func    TION__); [Super didreceivememorywarning];} View destroyed-(void) Dealloc {NSLog (@ "%s", __function__);}

View Printing results

2017-03-01 18:03:41.577 viewcontrollerlifecircle[32254:401790]-[viewcontroller initWithCoder:]2017-03-01 18:03:41.579 viewcontrollerlifecircle[32254:401790]-[viewcontroller awakefromnib]2017-03-01 18:03:41.581 VIEWCONTROLLERLIFECIRCLE[32254:401790]-[viewcontroller loadview]2017-03-01 18:03:46.485 ViewControllerLifeCircle[ 32254:401790]-[viewcontroller viewdidload]2017-03-01 18:03:46.486 viewcontrollerlifecircle[32254:401790]-[ Viewcontroller viewwillappear:]2017-03-01 18:03:46.487 viewcontrollerlifecircle[32254:401790]-[ViewController viewwilllayoutsubviews]2017-03-01 18:03:46.488 viewcontrollerlifecircle[32254:401790]-[ViewController viewdidlayoutsubviews]2017-03-01 18:03:46.488 viewcontrollerlifecircle[32254:401790]-[ViewController viewwilllayoutsubviews]2017-03-01 18:03:46.488 viewcontrollerlifecircle[32254:401790]-[ViewController viewdidlayoutsubviews]2017-03-01 18:03:46.490 viewcontrollerlifecircle[32254:401790]-[ViewController viewdidappear:]2017-03-01 19:03:13.308 Viewcontrollerlifecircle[32611:427962]-[viewcontroller viewwilldisappear:]2017-03-01 19:03:14.683 viewcontrollerlifecircle[32611:427962]-[viewcontroller viewdiddisappear:]2017-03-01 19:03:14.683 viewcontrollerlifecircle[32611:427962]-[viewcontroller dealloc]2017-03-01 19:12:05.927 ViewControllerLifeCircle[ 32611:427962]-[viewcontroller didreceivememorywarning]

Analysis
1. initWithNibName:bundle :
Initializes UIViewController , performs critical data initialization operations, and StoryBoard calls this method for non-creation UIViewController .
Note: Do not do this here View , View initialize it in the loadView method.

2. initWithCoder:
If StoryBoard view management is used, the program is not initialized directly UIViewController , StoryBoard automatically initialized segue , or automatically initialized when triggered, so the method is initWithNibName:bundle not called, but is initWithCoder called.

3. awakeFromNib
When the awakeFromNib method is called, all views are outlet action connected, but not yet determined, and this method can be used as an instantiation mate for the view controller, because some of the content that needs to be set according to the user's washing, cannot exist storyBoard or xib , so it can be awakeFromNib loaded in the method.

4. loadView
When executing to a loadView method, if the view controller is nib created by, then the view controller has been unpacked from the nib file and created, and the next task is to view initialize it.

loadViewThe method is UIViewController called when the object is view accessed and is empty. This is awakeFromNib a difference between it and the method.
Suppose we dispose of a property when dealing with a memory warning view : self.view = nil . Therefore loadView , the method may be called multiple times during the life cycle of the view controller.
loadViewMethods should not be called directly, but are called by the system. It loads or creates a view and assigns it a value to UIViewController the view property.

In the view process of creation, the first is nibName to find the corresponding nib file and then load. If it is nibName empty or cannot find the corresponding nib file, an empty view is created (this is typically pure code)

Note: Do not invoke the method of the parent class when overriding the Loadview method.

5. viewDidLoad
When loadView view it is loaded into memory, the method is further called viewDidLoad to make further settings. At this point, the view level has been put into memory, usually, we have a variety of initialization data loading, initial settings, modify constraints, remove views and many other operations can be implemented in this method.

View hierachy: Because each view has its own child view, this view hierarchy can also be understood as a tree-like data structure. and the root node of the tree, that is 根视图(root view) , in the UIViewController view attribute. It can be seen as a container for all other child views, that is, the root node.
6. viewWillAppear
After loading all the data, the system will display the view on the screen, this method will be called first, and usually we will make further settings in this method for the view that will be displayed. For example, how to display the device in different directions, set the status bar orientation, set the view display style, and so on.

On the other hand, when APP there are multiple views, the hierarchy view switch will also call this method, if the view is called when the data needs to be updated, it can only be implemented within this method.

7. viewWillLayoutSubviews
viewis about to lay it out Subviews . Such view as bounds changes (for example: the status bar is never displayed to the display, the view direction changes), to adjust Subviews the position, before the adjustment to do the work can be put in the method to implement

8.viewDidLayoutSubviews
viewIt has been laid out Subviews , where you can place the work that needs to be done after the adjustment is complete.

9.viewDidAppear
This method is called when view is added to the view level and multi-view, and the view that is being displayed can be further set here.

. viewWillDisappear
When the view is toggled, the current view is about to be removed, or is overwritten, and the method is called, which is not called at this time removeFromSuperview .

11.viewDidDisappear
viewHas disappeared or been overwritten, has been called at this time removeFromSuperView ;

12.dealloc
The view is destroyed, and this time you need to init release the objects you created in and viewDidLoad .

. didReceiveMemoryWarning
In the case of sufficient memory, app```的视图通常会一直保存在内存中,但是如果内存不够,一些没有正在显示的 Viewcontroller 就会收到内存不足的警告,然后就会释放自己拥有的视图,以达到释放内存的目的。但是系统只会释放内存,并不会释放对象的所有权,所以通常我们需要在这里将不需要显示在内存中保留的对象释放它的所有权,将其指针置 Nil '.

Three. The life course of the view
  • [ViewController initWithCoder:] or [ViewController initWithNibName:Bundle] : first load the object from the archive file UIViewController . Even pure code is nil passed as a parameter to the latter.
  • [UIView awakeFromNib]:As an assistant to the first method, the method handles some additional settings.
  • [ViewController loadView] : creates or loads a view property that assigns it to a UIViewController value view .
    - [ViewController viewDidLoad] : The whole 视图层次(view hierarchy) is now in memory, you can remove some views, modify constraints, load data, and so on.
  • [ViewController viewWillAppear:] : The view load is complete and will be displayed on the screen. Not yet animated, you can change the current screen orientation or status bar style, and so on.
  • [ViewController viewWillLayoutSubviews] : The Child View location layout is about to begin
  • [ViewController viewDidLayoutSubviews] : The location layout for the notification view has been completed
  • [ViewController viewDidAppear:] : The view has been displayed on the screen, so you can make some changes to the display effect on the image.
  • [ViewController viewWillDisappear:] : The view is about to disappear
  • [ViewController viewDidDisappear:] : The view has disappeared four: summary:
  • Only init the series of methods, such as the initWithNibName need to call themselves, other methods such as loadView and awakeFromNib then the system is automatically called. viewWill/Didthe methods of the series are similar to callbacks and notifications and are automatically called.

  • You need to be aware of plain code write view layouts, to call loadView methods manually, and not to call methods of the parent class loadView . The only difference between pure code and use is in the IB loadView method and before, which is the method to be aware of when programming loadView .

  • In initWithNibName addition awakeFromNib to working with the view controller, the other method is to process the view. These two methods are called only once in the life cycle of the view controller.



Transferred from: Http://www.jianshu.com/p/d60b388b19f5

iOS program execution sequence and Uiviewcontroller life cycle (grooming)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.