App Programming Guide for iOS翻譯
The App Life Cycle
譯:App生命周期
Apps are a sophisticated interplay between your custom code and the system frameworks. The system frameworks provide the basic infrastructure that all apps need to run, and you provide the code required to customize that infrastructure and give the app the look and feel you want. To do that effectively, it helps to understand a little bit about the iOS infrastructure and how it works.
譯:應用程序是一個您的自定義代碼和系統框架之間復雜地相互影響。系統框架提供所有應用程序都需要運行的基礎架構和你提供所需的自定義代碼,讓你的應用程序看起來像你想要的那樣。為了有效地去這樣做,有必要去了解一點關于iOS基礎架構和它是如何工作的。
iOS frameworks rely on design patterns such as model-view-controller and delegation in their implementation. Understanding those design patterns is crucial to the successful creation of an app. It also helps to be familiar with the Objective-C language and its features. If you are new to iOS programming, read Start Developing iOS Apps (Swift) for an introduction to iOS apps and the Objective-C language.
譯:iOS框架依賴于設計模式,如模型-視圖-控制器和代理實現。要成功創建一個應用程序,理解這些設計模式是至關重要的。它也有助于更加熟悉objective - c語言及其特性。如果你是iOS編程新手,請閱讀關于iOS apps和Objective-C語言介紹文檔 Start Developing iOS Apps (Swift)。
The Main Function
譯:Main函數
The entry point for every C-based app is the main function and iOS apps are no different. What is different is that for iOS apps you do not write the main function yourself. Instead, Xcode creates this function as part of your basic project. Listing 2-1 shows an example of this function. With few exceptions, you should never change the implementation of the main function that Xcode provides.
譯:每一個基于c語言的應用程序的入口點都是是main函數,iOS應用程序也一樣。iOS應用程序不同的是你自己不需要寫main函數。相反,Xcode創建這個main函數作為基本項目的一部分。表2-1顯示了這個函數的一個例子。除了少數例外,你永遠不應該改變Xcode提供的main函數的實現。
Listing 2-1 The main function of an iOS app
譯:一個iOS app的main函數
<code>
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[])
{
@autoreleasepool{
return UIApplicationMain(argc, argv, nil,NSStringFromClass([AppDelegate class]));}
}
</code>
The only thing to mention about the main function is that its job is to hand control off to the UIKit framework. The UIApplicationMain function handles this process by creating the core objects of your app, loading your app’s user interface from the available storyboard files, calling your custom code so that you have a chance to do some initial setup, and putting the app’s run loop in motion. The only pieces that you have to provide are the storyboard files and the custom initialization code.
譯:關于main函數唯一需要提及是它的職責:UIKit框架切換控制。UIApplicationMain函數主要用來創建應用程序的核心對象這個過程,從可用故事板文件中加載應用程序的用戶界面,調用您的自定義代碼,讓你有機會去做一些初始化設置,開啟應用程序的run loop運行循環。唯一一件你必須要做的事是提供的故事板文件和自定義初始化代碼。
The Structure of an App
譯:App應用架構
During startup, the UIApplicationMain function sets up several key objects and starts the app running. At the heart of every iOS app is the UIApplication object, whose job is to facilitate the interactions between the system and other objects in the app. Figure 2-1 shows the objects commonly found in most apps, while Table 2-1 lists the roles each of those objects plays. The first thing to notice is that iOS apps use a model-view-controller architecture. This pattern separates the app’s data and business logic from the visual presentation of that data. This architecture is crucial to creating apps that can run on different devices with different screen sizes.
譯:在啟動期間,UIApplicationMain函數設置幾個key對象和啟動應用程序運行。每個iOS應用程序的核心是UIApplication對象,他們的工作是促進系統和應用程序中的其他對象之間的交互。圖2 - 1顯示了大多數應用程序中對象通常位置,在表2 - 1列出了每個對象扮演的角色。首先要注意的是,iOS應用程序使用一個模型-視圖-控制器體系結構。這種模式將數據和業務邏輯從應用程序可視化數據中分離出來。為了創建應用程序可以運行在不同的屏幕尺寸的各種設備上,這個架構是至關重要的
Figure 2-1 App中關鍵對象
Table 2-1 The role of objects in an iOS app
譯:表2-1 iOS app中的對象角色
Object | Description |
---|---|
UIApplication object | The UIApplication object manages the event loop and other high-level app behaviors. It also reports key app transitions and some special events (such as incoming push notifications) to its delegate, which is a custom object you define. Use the UIApplication object as is—that is, without subclassing. |
App delegate object | The app delegate is the heart of your custom code. This object works in tandem with the UIApplication object to handle app initialization, state transitions, and many high-level app events. This object is also the only one guaranteed to be present in every app, so it is often used to set up the app’s initial data structures. |
Documents and data model objects | Data model objects store your app’s content and are specific to your app. For example, a banking app might store a database containing financial transactions, whereas a painting app might store an image object or even the sequence of drawing commands that led to the creation of that image. (In the latter case, an image object is still a data object because it is just a container for the image data.)Apps can also use document objects (custom subclasses of UIDocument) to manage some or all of their data model objects. Document objects are not required but offer a convenient way to group data that belongs in a single file or file package. For more information about documents, see Document-Based App Programming Guide for iOS. |
View controller objects | View controller objects manage the presentation of your app’s content on screen. A view controller manages a single view and its collection of subviews. When presented, the view controller makes its views visible by installing them in the app’s window.The UIViewController class is the base class for all view controller objects. It provides default functionality for loading views, presenting them, rotating them in response to device rotations, and several other standard system behaviors. UIKit and other frameworks define additional view controller classes to implement standard system interfaces such as the image picker, tab bar interface, and navigation interface.For detailed information about how to use view controllers, see View Controller Programming Guide for iOS. |
UIWindow object | A UIWindow object coordinates the presentation of one or more views on a screen. Most apps have only one window, which presents content on the main screen, but apps may have an additional window for content displayed on an external display.To change the content of your app, you use a view controller to change the views displayed in the corresponding window. You never replace the window itself.In addition to hosting views, windows work with the UIApplication object to deliver events to your views and view controllers. |
View objects, control objects, and layer objects | Views and controls provide the visual representation of your app’s content. A view is an object that draws content in a designated rectangular area and responds to events within that area. Controls are a specialized type of view responsible for implementing familiar interface objects such as buttons, text fields, and toggle switches.The UIKit framework provides standard views for presenting many different types of content. You can also define your own custom views by subclassing UIView (or its descendants) directly.In addition to incorporating views and controls, apps can also incorporate Core Animation layers into their view and control hierarchies. Layer objects are actually data objects that represent visual content. Views use layer objects intensively behind the scenes to render their content. You can also add custom layer objects to your interface to implement complex animations and other types of sophisticated visual effects.> |
譯
對象 | 描述 |
---|---|
UIApplication 對象 | UIApplication對象管理事件循環和其他應用程序高級行為。它還報告應用狀態轉換關鍵信息和一些特殊事件(如進入推送通知)的委托(這是您定義自定義一個對象)。UIApplication對象沒有子類,請直接使用這個類。 |
App delegate 對象 | 應用程序委托代理是自定義代碼關鍵。這個對象與UIApplication對象相配合來處理應用程序初始化,狀態轉換,許多應用程序高級事件。這個對象在每一個應用程序中保證也是唯一一個,所以它通常用于設置應用程序的數據結構初始化。 |
Documents 和 data 模型對象 | Data模型對象存儲應用程序的內容和特殊方面。例如,一個銀行應用程序可能存儲數據庫包含金融交易,而繪畫應用可能存儲圖像對象甚至創建圖像的繪制命令順序。(在后一種情況,一個圖像對象仍然是一個數據對象,因為它只是一個圖像數據的容器)。App也可以用document對象(自定義UIDocument子類)管理的部分或全部data模型對象。document對象不是必需的,但提供了一個方便的方式去組織屬于單個文件或文件包的數據關于文件的更多信息,請參見Document-Based App Programming Guide for iOS |
View controller 對象 | View controller對象管理你的應用程序在屏幕上顯示的內容。一個View controller管理單一視圖和它的子視圖的集合。顯示它管理的視圖時,View controller將它管理的視圖加載到應用程序的Window上。UIViewController類是所有View controller對象的基類。它提供了加載視圖、顯示視圖、當設備選擇時旋轉視圖等默認功能和其它幾個系統行為。UIKit和其他框架定義添加到視圖控制器類來實現標準系統接口,如圖像選擇器、標簽欄界面,導航界面。有關如何使用視圖控制器的詳細信息,參見View Controller Programming Guide for iOS。 |
UIWindow 對象 | UIWindow對象是其它一個或多個視圖在屏幕上參照坐標系。大多數應用程序只有一個窗口,用來在主屏幕上呈現內容,但是應用程序可能有一個額外的窗口用來在外接顯示器上顯示。改變你的應用的內容,您可以使用一個view controller來改變顯示在對應的窗口上它管理的視圖,永遠不會取代窗口本身。除了托管視圖作用外,windows替UIApplication對象傳遞事件給視圖和視圖控制器。 |
View 對象, control 對象, layer 對象 | View和control提供的可視化顯示應用程序的內容。View是一個將內容顯示在指定的矩形區域內和響應事件的對象,。control是一種專門實現視圖響應界面對象(如按鈕、文本框,切換開關。UIKit框架提供了標準視圖顯示許多不同類型的內容。您還可以直接通過UIView子類(或它的孫類)自定義視圖。除了合并View和control外,應用程序也可以將核心動畫層納入View和control層次結構。Layer對象實際上是代表視覺內容的數據對象。視圖使用Layer對象集中在幕后渲染它的內容。您還可以添加自定義layer對象接口來實現復雜的動畫和其他類型的復雜的視覺效果。 |
What distinguishes one iOS app from another is the data it manages (and the corresponding business logic) and how it presents that data to the user. Most interactions with UIKit objects do not define your app but help you to refine its behavior. For example, the methods of your app delegate let you know when the app is changing states so that your custom code can respond appropriately.
譯:區分一個iOS app與其他app不同處是從它的數據管理(和相應的業務邏輯),以及它如何呈現這些數據給用戶。大多數用UIKit對象的交互并不定義應用程序但幫助你改進它的行為。例如,應用程序委托的方法讓你知道當應用程序什么時候改變狀態,這樣你就可以自定義代碼適當地做出響應。
The Main Run Loop
譯:主運行循環
An app’s main run loop processes all user-related events. The UIApplication object sets up the main run loop at launch time and uses it to process events and handle updates to view-based interfaces. As the name suggests, the main run loop executes on the app’s main thread. This behavior ensures that user-related events are processed serially in the order in which they were received.
譯:一個應用程序的主運行循環處理所有用戶相關的事件。UIApplication對象在app啟動時設置主運行循環和使用它來處理事件和處理基礎視圖界面更新。顧名思義,主運行循環執行應用程序的主線程。這種行為可以確保接收用戶相關的事件是按順序連續處理的。
Figure 2-2 shows the architecture of the main run loop and how user events result in actions taken by your app. As the user interacts with a device, events related to those interactions are generated by the system and delivered to the app via a special port set up by UIKit. Events are queued internally by the app and dispatched one-by-one to the main run loop for execution. The UIApplication object is the first object to receive the event and make the decision about what needs to be done. A touch event is usually dispatched to the main window object, which in turn dispatches it to the view in which the touch occurred. Other events might take slightly different paths through various app objects.
譯:圖2 - 2顯示了主運行循環架構體系以及用戶事件導致應用程序采取行動的結果。當用戶與設備進行交互,這些交互相關事件由系統生成并通過一個特殊UIKit設置的接口交付給應用程序。所有事件在應用程序內部排隊并且一個接一個分配到主運行循環執行。UIApplication對象是第一個接收到事件的對象和決定需要做些什么。觸摸事件通常是派往主窗口對象,進而將該事件發送到被觸摸視圖中。其他事件可能會略有不同的路徑通過應用程序的各種對象。
Figure 2-2 Processing events in the main run loop
譯:主運行循環事件處理
Many types of events can be delivered in an iOS app. The most common ones are listed in Table 2-2. Many of these event types are delivered using the main run loop of your app, but some are not. Some events are sent to a delegate object or are passed to a block that you provide. For information about how to handle most types of events—including touch, remote control, motion, accelerometer, and gyroscopic events—see Event Handling Guide for iOS.
譯:在一個iOS應用程序許多事件類型可以被傳遞。最常見的類型列在表2 - 2。這些事件類型傳遞使用應用程序的主運行循環,但有些不是。一些事件被發送到一個委托對象或傳遞或通過你提供的Block代碼塊傳遞。如何處理大多數事件類型的信息--包括觸摸,遠程控制,運動,加速度計和陀螺事件,請查看 Event Handling Guide for iOS。
Table 2-2 Common types of events for iOS apps
譯:iOS應用程序事件常見類型
Event type | Delivered to… | Notes |
---|---|---|
Touch | The view object in which the event occurred | Views are responder objects. Any touch events not handled by the view are forwarded down the responder chain for processing. |
Remote control、Shake motion events | First responder object | Remote control events are for controlling media playback and are generated by headphones and other accessories. |
Accelerometer、Magnetometer、Gyroscope | The object you designate | Events related to the accelerometer, magnetometer, and gyroscope hardware are delivered to the object you designate. |
Location | The object you designate | You register to receive location events using the Core Location framework. For more information about using Core Location, see Location and Maps Programming Guide. |
Redraw | The view that needs the update | Redraw events do not involve an event object but are simply calls to the view to draw itself. The drawing architecture for iOS is described in Drawing and Printing Guide for iOS. |
譯
事件類型 | 響應者 | 備注 |
---|---|---|
觸摸 | 視圖對象事件 | 視圖是響應者對象。任何觸摸事件不是由視圖處理,而是轉發到響應者鏈進行處理。 |
遠程控制、搖晃運動事件 | 第一響應者對象 | 遠程控制事件用來控制媒體播放和是由耳機或其他配件產生的。 |
加速計、磁強計、陀螺儀 | 由你指定 | 加速度計、磁強計和陀螺儀硬件產生的事件傳遞到您指定的對象 |
位置 | 由你指定 | 使用核心位置框架來注冊接收位置事件的對象。更多關于使用位置核心信息,請參閱Location and Maps Programming Guide。 |
重繪 | 視圖更新 | 重繪事件不涉及事件接收對象,而僅僅是調用視圖本身去重繪自己。iOS繪畫架構描述請參閱Drawing and Printing Guide for iOS。 |
Some events, such as touch and remote control events, are handled by your app’s responder objects. Responder objects are everywhere in your app. (The UIApplication object, your view objects, and your view controller objects are all examples of responder objects.) Most events target a specific responder object but can be passed to other responder objects (via the responder chain) if needed to handle an event. For example, a view that does not handle an event can pass the event to its superview or to a view controller.
譯:一些事件,比如觸摸和遠程控制事件,是由你的應用響應者對象處理。在你的應用程序響應者對象到處都是。(UIApplication對象,你的視圖對象,你的視圖控制器對象都是響應者對象)大多數事件指定特定的響應者對象,但可以傳遞給其他響應者對象(通過響應者鏈)如果需要處理一個事件。例如,視圖對象不能處理一個事件時,可以將事件傳遞給它的父視圖或視圖控制器。
Touch events occurring in controls (such as buttons) are handled differently than touch events occurring in many other types of views. There are typically only a limited number of interactions possible with a control, and so those interactions are repackaged into action messages and delivered to an appropriate target object. This target-action design pattern makes it easy to use controls to trigger the execution of custom code in your app.
譯:發生在控件(如按鈕)的觸摸事件(比如按鈕)不同于發生在其他類型的視圖的觸摸事件,而是直接處理。控件通常只有數量有限的交互作用,因此這些交互重新包裝成動作消息交付給一個適當的目標對象。這種目標-操作的設計模式使它容易使用控件來觸發執行應用程序相應的自定義代碼。
Execution States for Apps
譯:app執行狀態
At any given moment, your app is in one of the states listed in Table 2-3. The system moves your app from state to state in response to actions happening throughout the system. For example, when the user presses the Home button, a phone call comes in, or any of several other interruptions occurs, the currently running apps change state in response. Figure 2-3 shows the paths that an app takes when moving from state to state.
譯:在任何時刻,你的應用程序只能處于表2 - 3中其中的一個狀態。系統將你的應用程序從一個狀態轉換到另一個狀態去響應系統發生的動作。例如,當用戶按下Home按鈕,一個電話進來,或任何其他中斷事件發生時,當前運行的應用程序改變狀態去響應。圖2 - 3所示應用程序從一個狀態轉換到另外一個狀態的行為路徑。
Table 2-3 App states
譯:app裝填
State | Description |
---|---|
Not running | The app has not been launched or was running but was terminated by the system. |
Inactive | The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state. |
Active | The app is running in the foreground and is receiving events. This is the normal mode for foreground apps. |
Background | The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state. For information about how to execute code while in the background, see Background Execution. |
Suspended | The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. |
譯
狀態 | 描述 |
---|---|
未運行 | 應用程序沒有啟動或被系統終止運行。 |
不活躍 | 應用程序在前臺運行但目前不接收事件。(但是可以執行其他代碼。)應用程序轉換到另一個狀態時通常短暫地存在于這個狀態。 |
活躍 | 應用程序是在前臺運行和可接收事件。這是前臺應用的正常模式。 |
后臺 | 應用程序在后臺執行代碼。大多數應用程序短暫地進入這種狀態直到被暫停。然而,一個應用程序請求額外的執行時間可能保持在這個狀態一段時間。此外,應用程序啟動后直接進入后臺時進入這種狀態,而不是不活躍的狀態。關于如何在后臺執行代碼信息,同時參閱Background Execution。 |
暫停 | 應用程序在后臺但不執行代碼時,系統自動將應用程序移動到這個狀態,沒有提前通知他們。當暫停時,應用程序仍在內存中但不執行任何代碼。 |
When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.
譯:當低內存發生時,系統可能會清除掉暫停使用的應用程序并且沒有通知,從而讓前臺擁有更多的內存空間。
Figure 2-3 State changes in an iOS app
譯:iOS app狀態轉換
Most state transitions are accompanied by a corresponding call to the methods of your app delegate object. These methods are your chance to respond to state changes in an appropriate way. These methods are listed below, along with a summary of how you might use them.
譯:大多數狀態轉換是伴隨著相應的調用應用程序委托對象的方法。這些方法你有機會以一個適當的方式應對狀態改變。下面列出了這些方法以及如何使用它們的摘要。
- application:willFinishLaunchingWithOptions:—This method is your app’s first chance to execute code at launch time.
譯:application:willFinishLaunchingWithOptions:—這方法是應用程序在啟動時第一個執行代碼的機會
- application:didFinishLaunchingWithOptions:—This method allows you to perform any final initialization before your app is displayed to the user.
譯:application:didFinishLaunchingWithOptions:—這種方法允許您執行應用程序顯示給用戶之前任何最終的初始化。
- applicationDidBecomeActive:—Lets your app know that it is about to become the foreground app. Use this method for any last minute preparation.
譯:applicationDidBecomeActive:—允許應用程序知道它即將成為前臺應用程序,使用這種方法對于界面顯示前最后一分鐘的準備 。
- applicationWillResignActive:—Lets you know that your app is transitioning away from being the foreground app. Use this method to put your app into a quiescent state.
譯:applicationWillResignActive:—讓你知道你的應用程序即將遠離前臺運行狀態。使用此方法來把你的應用程序到一個不活躍的狀態。
- applicationDidEnterBackground:—Lets you know that your app is now running in the background and may be suspended at any time.
譯:applicationDidEnterBackground:—讓你知道,現在你的應用程序在后臺運行,隨時可能會暫停。
- applicationWillEnterForeground:—Lets you know that your app is moving out of the background and back into the foreground, but that it is not yet active.
譯:applicationWillEnterForeground:—讓你知道你的應用從后臺回到前臺,但這尚不活躍。
- applicationWillTerminate:—Lets you know that your app is being terminated. This method is not called if your app is suspended.
譯:applicationWillTerminate:—讓你知道你的應用程序即將被終止。如果你的應用程序暫停是不會調用這個方法。
App Termination
譯:app終止
Apps must be prepared for termination to happen at any time and should not wait to save user data or perform other critical tasks. System-initiated termination is a normal part of an app’s life cycle. The system usually terminates apps so that it can reclaim memory and make room for other apps being launched by the user, but the system may also terminate apps that are misbehaving or not responding to events in a timely manner.
譯:應用程序必須準備好隨時發生終止,不應該等待保存用戶數據或執行其他重要任務。系統進行終止是一個正常的應用程序生命周期的一部分。系統通常終止應用程序,以便它可以回收內存,為其他由用戶發起應用程序提供內存空間,但系統也可能終止應用程序錯誤或不及時響應事件。
Suspended apps receive no notification when they are terminated; the system kills the process and reclaims the corresponding memory. If an app is currently running in the background and not suspended, the system calls the applicationWillTerminate: of its app delegate prior to termination. The system does not call this method when the device reboots.
譯:暫停狀態的應用程序終止時沒有收到通知;系統殺死進程并收回相應的內存。如果一個應用程序目前在后臺運行,而不是暫停時,系統優先調用其應用程序代理方法applicationWillTerminate:終止。設備重新啟動時系統沒有調用這個方法。
In addition to the system terminating your app, the user can terminate your app explicitly using the multitasking UI. User-initiated termination has the same effect as terminating a suspended app. The app’s process is killed and no notification is sent to the app.
譯:除了系統終止應用程序外,用戶可以使用多任務界面顯式地終止應用程序。用戶發起的終止與終止暫停的app有著同樣的效果。應用程序被殺掉的,及沒有通知發送給應用程序。
Threads and Concurrency
譯:線程及并發性
The system creates your app’s main thread and you can create additional threads, as needed, to perform other tasks. For iOS apps, the preferred technique is to use Grand Central Dispatch (GCD), operation objects, and other asynchronous programming interfaces rather than creating and managing threads yourself. Technologies such as GCD let you define the work you want to do and the order you want to do it in, but let the system decide how best to execute that work on the available CPUs. Letting the system handle the thread management simplifies the code you must write, makes it easier to ensure the correctness of that code, and offers better overall performance.
譯:系統在主線程上創建應用程序的,您可以根據需要創建額外的線程執行其他任務。對于iOS應用程序,首選技術是使用中央調度(GCD),操作對象,和其他異步編程接口,而不是自己創建和管理線程。GCD這種技術讓你定義你想做的工作和命令你想做的事,但讓系統決定如何最好地讓cpu執行工作。讓系統處理線程管理簡化了您必須編寫的代碼,讓它更容易保證代碼的正確性,并提供更好的整體性能。
When thinking about threads and concurrency, consider the following:
譯:當考慮線程和并發性時,考慮以下幾點:
- Work involving views, Core Animation, and many other UIKit classes usually must occur on the app’s main thread. There are some exceptions to this rule—for example, image-based manipulations can often occur on background threads—but when in doubt, assume that work needs to happen on the main thread.
譯:涉及到視圖、核心動畫,和許多其他UIKit類的工作通常必須發生在應用程序的主線程。在這條規則中有一些例外的例子,比如基礎圖像操作往往發生在后臺線程-當有不肯定時時,假設工作需要發生在主線程。
- Lengthy tasks (or potentially length tasks) should always be performed on a background thread. Any tasks involving network access, file access, or large amounts of data processing should all be performed asynchronously using GCD or operation objects.
譯:耗時任務(或潛在耗時的任務)應該一直在后臺線程中執行。任何涉及網絡訪問任務、文件訪問或大量的數據處理都應該用GCD或操作對象執行異步處理。
- At launch time, move tasks off the main thread whenever possible. At launch time, your app should use the available time to set up its user interface as quickly as possible. Only tasks that contribute to setting up the user interface should be performed on the main thread. All other tasks should be executed asynchronously, with the results displayed to the user as soon as they are ready.
譯:在啟動時,盡可能地把任務從主線程移除。在啟動時,應用程序應該使用可用的時間盡快建立起它的用戶界面。只有有助于建立用戶界面的任務應該放在主線程上執行。所有其他的任務應該是異步執行的,結果一準備好就顯示給用戶。
For more information about using GCD and operation objects to execute tasks, see Concurrency Programming Guide.
譯:關于使用GCD和操作對象更多信息,請查閱 Concurrency Programming Guide。