App Programming Guide for iOS<
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中关键对象
Snip20160924_1.pngTable 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
Snip20160924_2.png译:主运行循环事件处理
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
Snip20160924_3.png译: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。