The life cycle of an iOS app

Source: Internet
Author: User

In the development process we need some global objects to connect the various parts of the program, the most important of which is the UIApplication object. But in practical programming we do not deal directly with uiapplication objects, but with their agents.

UIApplication is the beginning of the iphone application and is responsible for initializing and displaying UIWindow, and is responsible for loading the first uiview of the application into the UIWindow form. Another task of uiapplication is to help manage the life cycle of the application, and uiapplication to perform this task through a proxy class named Uiapplicationdelegate. Although UIApplication is responsible for receiving events, Uiapplicationdelegate determines how the application responds to these events, uiapplicationdelegate the events that can be handled include the application Lifecycle events (such as program startup and shutdown), system events (such as incoming calls, warning alerts), this article describes how to load the application's UIView to UIWindow and how to handle system events using Uiapplicationdelegate.

It is usually not necessary for UIApplication readers to modify it, only to know uiapplication receive system events, and how to write code to handle these system events is the work of the programmer. Handling system events requires writing a class that inherits from the Uiapplicationdelegate interface, while the Uiapplicationdelegate interface provides life cycle functions to handle the application and system events of the application.

If you create a project with the Xcode template, Xcode creates a class that inherits from Uiapplicationdelegate for the programmer, but does not automatically implement optional event handlers that inherit from Uiapplicationdelegate. If the reader creates a project called "Testuiapplication", Xcode will To create TestUIApplicationAppDelegate.h and TESTUIAPPLICATIONAPPDELEGATE.M files, the file is declared as follows:
@interface Testuiapplicationappdelegate:nsobject <UIApplicationDelegate>
The application's uiapplication is defined in the Mainwindow.xib file and has a uiapplicationdelegate reference as a outlet.

The iPhone is not a multitasking operating system, so the application is vulnerable to interruptions, such as a call that could cause the application to lose focus, and if the phone is answered at this time, the application will automatically terminate the operation. There are many other similar events that cause the iphone application to lose focus, call the Applicationwillresignactive () method of the delegate class before the application loses focus, and the application will call when it gets to the focus again. Applicationdidbecomeactive () method. For example, when running the application, the lock screen invokes the Applicationwillresignactive () method of the delegate class, and when the screen is unlocked, the Applicationdidbecomeactive () method is called.

Another very important approach is applicationdidreceivememorywarning (), because the iphone device has only limited memory, and if the application is assigned too much memory the operating system terminates the application's operation. But before terminating, the operating system warns the application by calling the Applicationdidreceivememorywarning () method of the delegate class first, and after UIApplication receives the event it passes it to The Applicationdidreceivememorywarning () method of the delegate class, in which the delegate class can release memory operations to prevent the operating system from forcing the application to terminate.

Now let's look at what the methods defined in the agreement are to be implemented, respectively:
1,-(void) Applicationwillresignactive: (uiapplication *) application
Description: When the application is going to be inactive, during which time the application does not receive messages or events, such as coming to the phone
2,-(void) Applicationdidbecomeactive: (uiapplication *) application
Description: When the application executes in the active state, this is exactly the opposite of the method above
3,-(void) Applicationdidenterbackground: (uiapplication *) application
Description: Called when the program is pushed to the background. So to set the background to continue running, you can set it in this function
4,-(void) Applicationwillenterforeground: (uiapplication *) application
Description: Called when the program is going back to the foreground from the background, which is exactly the opposite of the method above.
5,-(void) Applicationwillterminate: (uiapplication *) application
Description: When the program is about to exit is called, it is usually used to save the data and some cleanup work before exiting. This needs to set the key value of the uiapplicationexitsonsuspend.
6,-(void) applicationdidreceivememorywarning: (uiapplication *) application
Description: The iphone device has only limited memory, and if the application is assigned too much memory the operating system will terminate the application's operation, this method will be executed before termination, usually can be done in the memory cleanup work to prevent the program from being terminated
7,-(void) Applicationsignificanttimechange: (uiapplication*) application
Description: Executes when the system time has changed
8,-(void) applicationdidfinishlaunching: (uiapplication*) application
Description: Executes when the program is loaded
9,-(void) application: (uiapplication) Application Willchangestatusbarframe: (cgrect) Newstatusbarframe
Description: Executes when the StatusBar box is going to change
10,-(void) application: (uiapplication*) Application willchangestatusbarorientation:
(uiinterfaceorientation) newstatusbarorientation
Duration: (nstimeinterval) duration
Description: Executed when the StatusBar box direction is going to change
11,-(BOOL) Application: (uiapplication*) Application Handleopenurl: (nsurl*) URL
Description: When executing via URL
12,-(void) application: (uiapplication*) Application didchangestatusbarorientation: (uiinterfaceorientation) Oldstatusbarorientation
Description: Executes when the StatusBar box direction changes
13,-(void) application: (uiapplication*) Application Didchangesetstatusbarframe: (cgrect) Oldstatusbarframe
Description: Executes when the StatusBar box changes

See the life cycle of iOS apps from "Hello World"

The first thing to do in iphone development is to know the iphone program life cycle, white point is when the program icon to start the program start to exit the program the entire use of the code in the process of what happened, only to understand this ability to master the development of the iphone program, Otherwise in the writing program when a bit muddy stiff don't know why the feeling. First forget the code template that Xcode generated for us, forget Xib forget IB, we personally write a Hello World program, although the actual development of the project does not need to do so the Xcode template and IB will do for us to do these chores, But now it is entirely up to us to write it, and rest assured that this program is a very simple Hello World program, and the code rarely adds up to 10 lines.

Before we begin, let's take a look at the Objective-c language's code for this Protocol:

    1. @protocol Simpleprotocol
    2. -(void) DoSomething: (NSString *) str;
    3. @end
    4. @interface simpleclass:nsobject< Simpleprotocol >{
    5. }
    6. @end
    7. @implementation Simpleclass
    8. -(void) DoSomething: (NSString *) str{
    9. NSLog (str);
    10. }
    11. @end

This is a simple protocol example, and the class Simpleclasss implements the protocol named Simpleprotocol. Protocols are very similar to interfaces in other languages, and it is useful to remember the implementation of this Protocol.

Next, use Xcode to create a new window-based application-type project named HelloWorld. In general, the project's file structure, the project generated by the Xcode template mainly contains classes (Hello World Appdelegate.h and Hello World appdelegate.m), and other Sources ( MAIN.M and Hello world_prefix.pch), Resources (Main window.xib and Hello World-info.plist), Frameworks (System framework provided by the IPhone SDK), Products (Hello World.app) these parts. Run this project directly in the simulator to see a white display interface program, so there is no line of code Xcode has generated a very simple project template for us.

Each iphone program contains a UIApplication object that manages the entire lifecycle of the program, starting with the loading of the first display, and listening to system events, program events, and the execution of the entire program. So where is the UI Application object in this simple project above? In this project we could not find any code about UI application, in fact the UI Application object in the project was initialized into memory by the UI application Main method, first opening the other Sources folder under the MAIN.M source file, which contains only a main method, and all the C program like this is the program entrance. The code is as follows:

    1. Int main (int argc, char *argv[])  {  
    2.      NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];   
    3.     int retval = uiapplicationmain (ARGC,&NBSP;ARGV,  nil, nil);   
    4.     [pool release];   
    5.      return retval;   
    6. }  

     in the main function, the second line of code UI application Main (argc, argv, nil, nil), the UIApplication object is initialized, this method in addition to ARGC And the argv parameter, this function also has 2 two string parameters to identify the UI application class and UI application proxy class, where the default is 2 nil, the first parameter is nil to initialize the UI application class as the default value. , you can use your own defined UI application subclass instead of nil. As for the second parameter, nil is set to nil and the Hello World Appdelegate class generated by the template is the default value. Here's the UI application object. What about a UI application proxy class object? It is necessary to illustrate that the UI Application object is to manage the life cycle of the entire program. Actually it is nothing specific to do, it is only responsible for monitoring the event when it is necessary to do the actual work of the UI application proxy class to do, UI Application is the equivalent of a herald who only communicates the command to the UI application proxy class, and then this soldier actually goes to the forefront, so you need to set the proxy class for the UI Application object.  

Very embarrassed to write a bunch of wordy text has not come to the point, but these wordy is very necessary, and now began to write our first iphone program HelloWorld. Above is not said to forget the code template, forget xib forget Interfcae builder, so we put the template auto-generated parts deleted, find other sources file main.m Delete, find the Classes folder Hello World Appdelegate.h and Hello World appdelegate.m Delete, the resources folder under the main window.xib delete, there is one thing must be done that is open the resources folder under Hello World-info.plist, then find the key "main nib file base name" removed because in the above we have removed the Main window.xib, so that the completion of the project cleanup, turned into a real empty project without what implementation code.

After finishing the above cleanup work, then open our writing, the first new program entry MAIN.M file has the main method, the program starts here! The code is as follows:

    1. int main (int argc, char *argv[]) {
    2. NSAutoreleasePool * Pool = [[NSAutoreleasePool alloc] init];
    3. int retVal = Uiapplicationmain (argc, argv, nil, @ "sampledelegate");
    4. [Pool release];
    5. return retVal;
    6. }

NSAutoreleasePool Memory Auto-release pool What do I say, you know. Here's a look at the second line of UI application main (argc, argv, nil, nil); Change to UI application main (argc, argv, nil, @ "sampledelegate") compared to template generation; In doing so, we have set the UI Application object named Sampledelegate proxy class, which is not to say that the UI application does not handle the specific things, the real thing is the UI application proxy class, The name of the Sampledelegate proxy class is that we need to specifically write code implementation, when the UI application initialized to start listening to events, according to different listening events to allow the Sampledelegate proxy class to do different processing, such as the display of the first display interface.

Create a new class named SAMPLEDELEGATE.M, and enter the following code in SampleDelegate.h:

    1. @interface sampledelegate:nsobject<uiapplicationdelegate> {
    2. }
    3. @end

      Notice No, sampledelegate:nsobject <UIApplicationDelegate> This is not very familiar, Looking at the top of the Objective-c language about protocol code, the Simpleclass class needs to implement the Simpleprotocol protocol definition, so uiapplicationdelegate is a protocol definition, The same sampledelegate also needs to implement the method defined in UI application delegate, except that the protocol is well-defined (see UI Application Delegate.h) and Simpleprotocol is our own definition, but to do the same thing, is sampledelegate need to implement the UI application Delegate protocol defined method, which is the UI The Application object notifies the UI Application object proxy class Sampledelegate the appropriate method to execute when the system changes. Below is the implementation code of Sampledelegate written in SAMPLEDELEGATE.M Note No, Sampledelegate:nsobject <UIApplicationDelegate> This is not very familiar with the wording, Looking at the top of the Objective-c language about protocol code, the Simpleclass class needs to implement the Simpleprotocol protocol definition, so the UI application delegate is a protocol definition, The same sampledelegate also needs to implement the method defined in UI application delegate, except that the protocol is well-defined (see UI Application Delegate.h) and Simpleprotocol is our own definition, but to do the same thing, is sampledelegate need to implement the UI application Delegate protocol defined method, which is the UI The Application object notifies the UI Application object proxy class Sampledelegate the appropriate method to execute when the system changes. The following is the implementation code of Sampledelegate written in SAMPLEDELEGATE.M:  

  1. @implementation Sampledelegate
  2. -(void) Applicationwillresignactive: (UIApplication *) application{}
  3. -(void) Applicationdidbecomeactive: (UIApplication *) application{}
  4. -(void) Applicationdidenterbackground: (UIApplication *) application{}
  5. -(void) Applicationwillenterforeground: (UIApplication *) application{}
  6. -(void) Applicationwillterminate: (UIApplication *) application{}
  7. -(void) applicationdidreceivememorywarning: (UIApplication *) application{}
  8. -(void) Applicationsignificanttimechange: (uiapplication*) application{}
  9. -(void) applicationdidfinishlaunching: (uiapplication*) application{}
  10. -(void) application: (uiapplication*) Application Willchangestatusbarframe: (CGRect) newstatusbarframe{}
  11. -(void) application: (uiapplication*) Application willchangestatusbarorientation: (uiinterfaceorientation) Newstatusbarorientation Duration: (nstimeinterval) duration{}
  12. -(BOOL) Application: (uiapplication*) Application Handleopenurl: (nsurl*) url{
  13. return YES;
  14. }
  15. -(void) application: (uiapplication*) Application didchangestatusbarorientation: (uiinterfaceorientation) oldstatusbarorientation{}
  16. -(void) application: (uiapplication*) Application Didchangesetstatusbarframe: (CGRect) oldstatusbarframe{}
  17. @end

Now let's look at what the methods defined in the agreement are to be implemented, respectively:

-(void) Applicationwillresignactive: (uiapplication *) application

Description: When the application is going to be inactive, during which time the application does not receive messages or events, such as coming to the phone

-(void) Applicationdidbecomeactive: (uiapplication *) application

Description: When the application executes in the active state, this is exactly the opposite of the method above

-(void) Applicationdidenterbackground: (uiapplication *) application

Description: Called when the program is pushed to the background. So to set the background to continue running, you can set it in this function

-(void) Applicationwillenterforeground: (uiapplication *) application

Description: Called when the program is going back to the foreground from the background, which is exactly the opposite of the method above.

-(void) Applicationwillterminate: (uiapplication *) application

Description: When the program is about to exit is called, it is usually used to save the data and some cleanup work before exiting. This needs to set the key value of the uiapplicationexitsonsuspend.

-(void) applicationdidreceivememorywarning: (uiapplication *) application

Description: The iphone device has only limited memory, and if the application is assigned too much memory the operating system will terminate the application's operation, this method will be executed before termination, usually can be done in the memory cleanup work to prevent the program from being terminated

-(void) Applicationsignificanttimechange: (uiapplication*) application

Description: Executes when the system time has changed

-(void) applicationdidfinishlaunching: (uiapplication*) application

Description: Executes when the program is loaded

-(void) application: (uiapplication) Application Willchangestatusbarframe: (cgrect) Newstatusbarframe

Description: Executes when the StatusBar box is going to change

-(void) application: (uiapplication*) Application willchangestatusbarorientation:

    1. (uiinterfaceorientation) newstatusbarorientation
    2. Duration: (nstimeinterval) duration

Description: Executed when the StatusBar box direction is going to change

-(BOOL) Application: (uiapplication*) Application Handleopenurl: (nsurl*) URL

Description: When executing via URL

-(void) application: (uiapplication*) Application didchangestatusbarorientation: (uiinterfaceorientation) Oldstatusbarorientation

Description: Executes when the StatusBar box direction changes

-(void) application: (uiapplication*) Application Didchangesetstatusbarframe: (cgrect) Oldstatusbarframe

Description: Executes when the StatusBar box changes

I summed up a approximate flowchart, not very accurate but basically also explains the whole process, for reference only.

So far our program has not seen anything, and indeed we have not written a specific function code, the next thing we want to do is to display on the screen "Hello world! ", first know to display on the screen, first need a UIWindow object, which you can think of as a television, and then also need to add UIView object to this UIWindow object, UIView equivalent to the scene on the television screen. By the above process know to show after the program can be processed in the Applicationdidfinishlaunching method, so modify the Applicationdidfinishlaunching method as follows:

    1. -(void) applicationdidfinishlaunching: (uiapplication*) application{
    2. UIWindow *window=[[uiwindow Alloc]initwithframe:[[uiscreen mainscreen] bounds];
    3. Sampleviewcontroller *viewctrl=[[sampleviewcontroller Alloc]init];
    4. [Window AddSubview:viewctrl.view];
    5. [Window makekeyandvisible];
    6. }

Here are a few things that are done in the code above:

Instantiated a UIWindow object

Instantiated the Sampleviewcontroller object

Add the Sampleviewcontroller object UIView object to the UIWindow object

Show UIWindow objects

Look at this code we did not directly instantiate a UIView object and then add to the UIWindow object and through the Sampleviewcontroller object, it is the Uiviewcontroller sub-class responsible for the display control of the view, very useful, Here we just realized the loadview is enough, we just have to show a simple "Hello world!" Text, the specific code is as follows:

  1. @interface Sampleviewcontroller:uiviewcontroller {}
  2. @end
  3. @implementation Sampleviewcontroller
  4. -(void) loadview{
  5. UIView *contentview = [[UIView alloc] Initwithframe:[[uiscreen Mainscreen] applicationframe]];
  6. Contentview.backgroundcolor = [Uicolor blackcolor];
  7. Self.view = Contentview;
  8. [Contentview release];
  9. CGRect labelframe = CGRectMake (40.0f, 200.0f, 240.0f, 60.0f);
  10. UILabel *frontlabel = [[UILabel alloc] initwithframe:labelframe];
  11. Frontlabel.text = @ "Hello world!";
  12. Frontlabel.font = [Uifont fontwithname:@ "Georgia" size:24.0f];
  13. Frontlabel.textcolor = [Uicolor colorwithred:0.82f green:1.0f blue:0.286f alpha:1.0f];
  14. Frontlabel.backgroundcolor = [Uicolor colorwithred:0.0f green:0.0f blue:0.0f alpha:0.0f];
  15. [Contentview Addsubview:frontlabel];
  16. [Frontlabel release];
  17. }
  18. @end

Here we have completed the preparation of the Hello World program, click to run to see the following:

The life cycle of an iOS app

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.