1. Introduction
Why is it called the life of the app? Tribute to the film "The Life of the abandoned pine nuts."
Self-study iOS east a hoe West a pickaxe total feeling does not have a general concept, or to look at official Internet cafes, first look at an app's entire life cycle, this article is mainly translated official documents: https://developer.apple.com/library/ios/ documentation/iphone/conceptual/iphoneosprogrammingguide/theapplifecycle/theapplifecycle.html#//apple_ref/doc/ Uid/tp40007072-ch2-sw1
App life cycle
Apps are in fact the product of complex integration of customer code and system frameworks. A specific system framework provides the most basic functionality for all the apps running in it, and the functionality of the specific apps needs to be implemented by the developers themselves. For the efficiency of subsequent development, this article helps you understand the fundamentals and working mechanisms of a little iOS framework.
The iOS framework is implemented with Model-view-controller and proxy design patterns. Understanding its design patterns is useful for developing an app. This also helps you to better understand and adapt to the objective-c language and its characteristics. If you're a novice iOS developer, the best way to get started is to read "developing iOS Apps Today".
Main function
Any program written in C-based language is a portal to the main function, and iOS apps are no exception. The only difference is that you don't need to implement the main function when you're writing an iOS app, and the Xcode tool will automatically create it for you when you create the project. Listing 2-1 shows an example of the main function. Generally you do not need to modify the default implementation that Xcode provides for you.
Listing 2-1 The main function of an IOS app
#import <uikit/uikit.h> #import appdelegate.h " int Main (int argc, char * argv[]) {@autoreleasepool { re Turn uiapplicationmain (argc, argv, Nil, Nsstringfromclass ([appdelegate class
The only thing to note is that the main function's task is to connect to the Uikit framework. The Uiapplicationmain function creates an applied and Hing object, loads the user interface information from the storyboard file, invokes the client code to initialize, and launches the Runloop function of the application. Throughout the process, user code initialization code and Storyborad files are required to be prepared by developers.
The structure of an app
During startup, the Uiapplicationmain function launches a number of key objects and starts the application. For any application, the Uiapplucation object is the core of the kernel, and the task of this object is to establish a communication mechanism between the system and the objects in the application. figure 2-1 shows the key objects in an app, while table 2-1 lists the functions of each object. The first thing to note is that the iOS app is using the Model-view-controller architecture. This pattern separates the applied data and business logic from the data persistence layer. This architecture is a key factor in how an application can run on devices of different screen sizes.
Figure 2-1 Key objects in an IOS app
|
Object |
Describe |
|
UIApplication对象
|
The UIApplication object manages event loops and other high-level application behavior. It is also responsible for generating the application's status recommendations and some special events (such as push notifications) to the user-defined agents. UIApplication in the use of the time not to sub-class him, direct use can. |
|
APP Delegate Objects
|
The agent applied is the core of the user code. This object and the UIApplication object are concatenated, responsible for initializing the application, state migration, and many high-level application practices. This object is necessarily present in every application, so it is often used to initialize the data for the application. |
|
Documents and Data Model object |
The Data model object stores the specific content of the application, and different applications have different object characteristics. For example, in a bank-class app you need a database object with financial transactions, and in a painting app you may need to have a picture object or an object to hold the drawing instructions to build your image. (The last Image object is ultimately a data object because he only contains specific information about a picture)
The application can also use the Document object (which can inherit uidocument) to manage some or all of the data Model objects. The Document object is not required, but he provides another convenient way to manage the data. For more information, refer to document-based App programmingGuide for IOS. |
|
View Controller Object |
Try the Controller object manager on your screen to display the content. A view controller manages a view and a set of sub-views of this attempt. When the view needs to be displayed, the view controller will attempt to install the windows that are displayed to the application.
UIViewController类是所有视图控制器的基类。它提供了很多基础的功能区加载视图,呈现试图、在设备旋转的时候去旋转视图和一些其他的标准的系统行为。UIKit和其他框架定义了一些额外的视图控制器去实现标准的系统接口诸片取得器,tab bar接口和导航接口等。
For information on how to use the view Controller, refer to View Controllers ProgrammingGuide for IOS. |
|
UIWindow对象
|
The UIWindow object is responsible for coordinating the display of one or more views on the screen. Most applications have only one window, and the main task is to render the content on the home screen, but the app can have an extra window to manage the external display.
When your app is running and the content is changed, the interior uses a view controller to change the view in the corresponding window, which is not changed or rebuilt for window.
In addition to loading views, window also passes events to the view or view controller along with the UIApplication object. |
|
view objects, control objects, and Layer objects |
Views and controls provide visual application information content. A view is an object that adds the content to a rectangular area of a specified size and only goes to the corresponding event in this rectangular area. controls is a special view, mainly system in order to provide some friendly built-in controls such as buttons, text boxes and switches. The
Uikit Framework provides a standard view to render different types of page content. You can also customize your own view by directly integrating UIView .
In addition to having views and controls, the app also provides the core animation layer at the view and control levels. A Layer object is actually a data object he paints a visual effect. The view uses layer objects to make the scene change. You can also add your own layered objects to complete complex, cool visuals. |
the difference between an application and another application is in the way that he manages the data (and the logic on top of the data) and presents the data to the user. Most behaviors that interact with Uikit framework objects do not define your application but help you to standardize behavior. For example, an app's agent notifies you that a state of your app has changed so that you can write code logic to handle the response.
Main Run Loop
The main run loop of an app handles all user-related time. The UIApplication object creates a main run loop at startup and uses it to handle event and view-based interface status updates. As its name, main run loop runs in the main thread. This ensures that user events are processed in an orderly order, first-to-first-processed.
Figure 2-2 shows the schema of main run loop and the process of user event handling. When the user operates the device, the system generates the corresponding event and forwards the event to the app via a dedicated port set by the Uikit framework. In the application the internal event will be arranged one by another forwarded to main run loop to execute. The UIApplication object is the first object to receive an event, and he will make a decision as to how this event should be handled. For touch events, it is usually forwarded to the main Window object, which then sends the object to the view where the touch event occurred. Other events are forwarded to the App object, but the forwarding path will be slightly different.
HTTP://HOME.CNBLOGS.COM/U/IOS123/Note: The following figure is still a little unclear, the event queue should belong to the application, not clearly expressed.
Figure 2-2 Processing events in the main run loop
iOS apps can accept and forward multiple types of events. The most common types of events are found in table 2-2. Most event types are forwarded using main run loop, but some are not. Many events are sent to the proxy object or directly to the block. For the system to handle most event types-including touch, remote, motion, accelerator, and gyroscope events, refer to Event handling guide for IOS.
Table 2-2 Common types of events for IOS apps
|
Event Type |
Forward to ... |
Note |
|
Touch Touches Event |
View of where the event occurred |
Views is responder objects. Any touch events isn't handled by the view is forwarded down the responder chain for processing.
A view is a responder object. Any touch event that is not handled by the target event will go into the responder chain and look for the handler to process it. |
|
Remote Control Event
Shake Motion Events
Shaking events |
First Responder |
Remote control events is for controlling media playback and is generated by headphones and other accessories.
Remote control events are triggered by the design of an additional device, such as a headset or remote control, that controls the streaming media. |
|
Accelerometer Accelerometer
Magnetometer magnetometer
Gyroscope Gyroscope |
The object you designate
Specifying objects |
Events related to the accelerometer, magnetometer, and gyroscope hardware is delivered to the object you designate.
Accelerometer, the hardware events associated with the gyroscope and magnetometer are forwarded to the pre-specified object for processing. |
|
Location |
The object you designate
Specifying objects |
You register to receive location events using the Core location framework. For more information about using the Core location, see Location and Maps programmingGuide.
You can use the core location framework to register and accept a positional event. The contents of the core location framework can be found in more detail in location and the Maps programmingGuide. |
|
Redraw Redraw |
The view that needs the update
View Updates |
Redraw events do not involve a event object but is simply calls to the view to draw itself. The drawing architecture for iOS are described in drawing and PrintingGuide for iOS.
Redraw event is not an event object but he simply goes to tell the view to redraw itself. A description of the drawing mechanism can be found in Drawing and PrintingGuide for IOS. |
Many events, such as touch events and remote control events, will be handled by the responder object being applied. The responder object may exist anywhere you apply ( UIApplication对象,视图对象和 视图控制器对象都可能是响应者 ) Most events specify a responder object but if events have special requirements, they can be passed to different objects through the responder chain mechanism. For example, a view that does not handle events can pass events to his superview or to a view controller.
Touch events caused by controls (such as buttons) are handled differently from touch events caused by other types of views. They usually wrap a target-action pair, and the target can be specified so that the developer can conveniently use space to control the processing logic.
Execution status of the app
At any time, your app will be in one of the states listed in table 2-3. The system will move your app from one state to another, and when the user presses the home button, when the phone is plugged in, or any other interruption occurs, the current running app will change state, and figure 2-3 shows the migration path between the app's state.
Table 2-3 App states
|
State |
Describe |
|
Not running |
The app has not been launched or is running but is terminated by the system.
The application has not been loaded or has been run but has been shut down by the system. |
|
Inactive |
The app is running in the foreground it's currently not receiving events. (It May is executing other code though.) An app usually stays in this state is briefly as it transitions to a different state.
The app is running in the foreground but is not currently accepting any time. An application is usually in this state when it is in a state of transition. |
|
Active |
The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
An app is running in the foreground and can accept time. This is the status of the normal foreground application. |
|
Background |
The app is in the background and executing code. Most apps enter the briefly on their-being suspended. However, an app, the requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly to the background enters this state instead of the inactive state. For information the what to execute code while in the background, see background execution.
The app is running in the background. Most applications are temporarily in this state when transitioning to suspended. However, when an application requires additional execution time, it will remain in this state for a period of time (programs that can be run in the background, such as navigating the horse). In addition, an application will go directly into the background state without going through the inactive state. You can refer to background execution for code execution in background state. |
|
Suspended |
The app is in the background, but isn't executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, a app remains in memory but does not execute any code.
When a low-memory condition occurs, the system could purge suspended apps without notice to make more space for the Foregrou nd app.
The system automatically transfers the application to this state when it is applied in the background state and there is no additional logic code to run. When in the suspended state, the application still maintains his memory space but does not execute any code, and when the low memory alarm occurs, the system may clean up these suspended applications in order for the foreground application to run smoothly. |
Figure 2-3 state changes in an IOS app
Most of the HU state migrations are accompanied by methods that invoke the proxy object. These methods give you the opportunity to do some extra processing for the change of state. These methods are as follows,
-
application:willFinishLaunchingWithOptions:-This method is called first when the application is loaded
-
application:didFinishLaunchingWithOptions:-Before the app renders on the screen, you can do some initialization action before the last chance.
-
applicationDidBecomeActive:-Triggers when your app's status is turned into a foreground run.
-
applicationWillResignActive:-triggered when the app has a state migration from the foreground running state.
-
applicationDidEnterBackground:-When your app is in a background state and is ready to cut into the suspended.
-
applicationWillEnterForeground:-When the app is transitioning from the background to the foreground but is not in the active state at this time.
-
applicationWillTerminate:-When the app is closed. This is not called when the application is in the suspended state.
application termination
The application must be ready to be terminated at any time and should not save data or other important tasks before being terminated. It is extremely normal for the system to terminate an application. The system typically kills background apps in order to free up memory space to run other apps, but the system may also kill apps without warning, so developers have the potential to be killed at any time.
Applications in the suspended state do not receive notification of in-app termination, and the system will kill the entry to free memory. If an app is running in the background while background is not in the suspended state, the system will callapplicationWillTerminate:代理方法来通知应用你要被干掉了。当然当设备被重启的时候可不要指望谁来通知你的应用。
In addition to the system termination scenario, the user may terminate the program, based on the user's termination behavior can be based on the system to kill the suspended state of the application behavior, the application will not receive any notification.
Threads and concurrency
The system creates an app's main thread and, if necessary, developers can create additional threads to run other tasks. For iOS apps, the developer's preferred multithreaded count is Gcd,operation objects and other asynchronous techniques, and it's very easy to avoid creating and managing threads on their own, which can be very error-prone and painful. GCD technology allows developers to customize how tasks are executed and executed sequentially, but at the bottom level the system will ultimately determine the best execution process. Having the system handle the execution of tasks allows developers to focus more on business and performance.
When you think about threading and concurrency, think about these points of note:
- When a task is run for a view, Core animation and other Uikit related classes, it is usually necessary to execute it in the main thread. There are some exceptions-for example, image-based processing is going to run in a background thread-but be sure to consider the rules if you have any questions.
- Long tasks should be run in the background thread, any and network, file read and big data processing should use GCD or Operation object to run concurrently without blocking the main thread, otherwise your application will appear stuck phenomenon.
- When the app loads, try not to run the task in the main thread. At the time of loading, your app should load the user interface as soon as possible to render to the user.
A detailed reference Concurrency programmingGuide for the technical section of the GCD and Operation objects.
[New Learn] the life of a rejected app