Mac应用编程指南之二——Mac应用程序环境

The Mac Application Environment

Mac应用程序环境

OS X incorporates the latest technologies for creating powerful and fun-to-use apps. But the technologies by themselves are not enough to make every app great. What sets an app apart from its peers is how it helps the user achieve some tangible goal. After all, users are not going to care what technologies an app uses, as long as it helps them do what they need to do. An app that gets in the user’s way is going to be forgotten, but one that makes work (or play) easier and more fun is going to be remembered.

OS X包含了最新的技术,用于创建强大而易用的应用。但技术本身并不足以使应用出彩。一个应用想要脱颖而出,就要能够帮助用户实现特定的目标。要知道,用户要求的是应用能帮助他们实现需要,而并不关心应用所使用的技术。一个碍事的应用会被遗忘,但一个使工作(或游戏)变得轻松和有趣的应用会被记住。

You use Cocoa to write apps for OS X. Cocoa gives you access to all of the features of OS X and allows you to integrate your app cleanly with the rest of the system. This chapter covers the key parts of OS X that help you create great apps. In particular, this chapter describes some of the important ease-of-use technologies introduced in OS X v10.7. For a more thorough list of technologies available in OS X, seeMac Technology Overview.

大家使用Cocoa来写OS X应用程序。Cocoa可供你访问OS X所有的特性,允许你的应用与系统融为一体。这一章涵盖了帮你创建伟大精彩的OS X应用的关键部分。尤其需要指出的是,这一章介绍了OS X v10.7引入的一些重要的、易用的技术。如果需要更关于OS X的更全面的技术列表,参考Mac Technology Overview



An Environment Designed for Ease of Use

以易用为宗旨的应用环境

OS X strives to provide an environment that is transparent to users and as easy to use as possible. By making hard tasks simple and getting out of the way, the system makes it easier for the user to be creative and spend less time worrying about the steps needed to make the computer work. Of course, simplifying tasks means your app has to do more of the work, but OS X provides help in that respect too.

OS X致力于提供向用户透明、尽可能易用的应用环境。通过简化或避开困难任务,使用户集中精力于创新,而不用耗费时间,去考虑使计算机正常工作的步骤。当然,简化任务意味着你的应用需要做更多的工作,但在这方面OS X提供了帮助。

As you design your app, you should think about the tasks that users normally perform and find ways to make them easier. OS X supports powerful ease-of-use features and design principles. For example:

当设计应用时,应当考虑用户使用应用所需要的操作,并找到简化的方法。OS X支持强大的易用特性和设计准则。比如:

  • Users should not have to save their work manually. The document model in Cocoa provides support for saving the user’s file-based documents without user interaction; seeThe Document Architecture Provides Many Capabilities for Free.
  • 用户不需要手动保存当前工作。Cocoa提供的文档模型支持自动保存用户基于文件的文档,不需要用户操作;参考The Document Architecture Provides Many Capabilities for Free.
  • Apps should restore the user’s work environment at login time. Cocoa provides support for archiving the current state of the app’s interface (including the state of unsaved documents) and restoring that state at launch time; seeUser Interface Preservation.
  • 在登录时,应用应当恢复用户熟悉的工作环境。Cocoa对保存应用当前状态和登录时恢复提供支持;参考User Interface Preservation.
  • Apps should support automatic termination so that the user never has to quit them. Automatic termination means that when the user closes an app’s windows, the app appears to quit but actually just moves to the background quietly. The advantage is that subsequent launches are nearly instant as the app simply moves back to the foreground; seeAutomatic and Sudden Termination of Apps Improve the User Experience
  • 应用应当支持自动结束,而不需要用户退出。自动结束意味着当用户关闭应用窗口的时候,应用貌似退出,实则静默地进入后台。这样做的优势是后续加载非常迅速,因为应用只是从后台移动到前台;参考Automatic and Sudden Termination of Apps Improve the User Experience
  • You should consider providing your users with an immersive, full-screen experience by implementing a full-screen version of your user interface. The full-screen experience eliminates outside distractions and allows the user to focus on their content; see Implementing the Full-Screen Experience.
  • 应用应当考虑实现全屏界面,为用户提供沉浸式体验。全屏可以排除外界干扰,使用户更加专注;参考Implementing the Full-Screen Experience.
  • Support trackpad gestures for appropriate actions in your app. Gestures provide simple shortcuts for common tasks and can be used to supplement existing controls and menu commands. OS X provides automatic support for reporting gestures to your app through the normal event-handling mechanism; see Cocoa Event Handling Guide.
  • 为应用的部分操作增加触控板手势支持。手势为通用任务提供简易的快捷方式,可用于代替控件和菜单命令。OS X通过事件处理机制,自动向你的应用报告手势变化;参考Cocoa Event Handling Guide.
  • Consider minimizing or eliminating the user’s interactions with the raw file system. Rather than expose the entire file system to the user through the open and save panels, some apps, in the manner of iPhoto and iTunes, can provide a better user experience by presenting the user’s content in a simplified browser designed specifically for the app’s content. OS X uses a well-defined file system structure that allows you to place and find files easily and includes many technologies for accessing those files; see The File System.
  • 考虑减少或排除用户与文件系统的交互。与其通过打开和保存对话框向用户展示整个文件系统,一些应用采取类似iPhotoiTunes的方式,专门设计了适合应用内容的简易浏览器来向用户展示,从而提供了更好的体验。OS X使用定义明确的文件结构系统,能很容易的放置、查找文件,还包括访问这些文件的技术;参考The File System.
  • For apps that support custom document types, provide a Quick Look plug-in so that users can view your documents from outside of your app; seeQuick Look Programming Guide.
  • 如果应用有自定义的文件类型,提供一个Quick Look插件,使用户不必打开应用,就能浏览文档;参考Quick Look Programming Guide.
  • Apps should support the fundamental features for the OS X user experience that make apps elegant and intuitive, such as direct manipulation and drag-and-drop.Users should remain in control, receive consistent feedback, and be able to explore because the app is forgiving with reversible actions; seemacOS Human Interface Guidelines.
  • 应用应该支持OS X用户体验的基本特性,使应用程序优雅的和直观,比如直接操做和拖放。用户应保持控制,收到一致的反馈,并能够进行尝试探索,应用应当支持撤销操作;参考macOS Human Interface Guidelines.

All of the preceding features are supported by Cocoa and can be incorporated with relatively little effort.

Cocoa支持以上所有特性,不用费力就可以集成。


A Sophisticated Graphics Environment

复杂的图形环境

High-quality graphics and animation make your app look great and can convey a lot of information to the user. Animations in particular are a great way to provide feedback about changes to your user interface. So as you design your app, keep the following ideas in mind:

高质量的图形和动画可以使用应用更加精彩,并能够向用户传递大量信息。一个好的作法是,用特殊的动画来提供用户界面变化的反馈。设计应用时,思考这些问题:

  • Use animations to provide feedback and convey changes. Cocoa provides mechanisms for creating sophisticated animations quickly in both the AppKit and Core Animation frameworks. For information about creating view-based animations, seeCocoa Drawing Guide. For information about using Core Animation to create your animations, seeCore Animation Programming Guide.
  • 使用动画来提供反馈、传递信息。在AppKitCore Animation框架中,Cocoa提供了快速创建复杂动画的机制。创建以视图为基础的动画,参考Cocoa Drawing Guide. 使用Core Animation创建动画,参考 Core Animation Programming Guide
  • Include high-resolution versions of your art and graphics. OS X automatically loads high-resolution image resources when an app runs on a screen whose scaling factor is greater than 1.0. Including such image resources makes your app’s graphics look even sharper and crisper on those higher-resolution screens.
  • 包含高分辨率的创意素材和图形版本。在缩放系数大于1.0的显示器上,OS X自动加载高分辨率的图片资源。在高分辨率的显示器上,包含这些图片资源会使应用界面更加清晰锐利。

For information about the graphics technologies available in OS X, seeMedia Layer in Mac Technology Overview.

关于OS X上可用的图形技术,参考Mac Technology Overview中的Media Layer


Low-Level Details of the Runtime Environment

运行环境的底层细节

When you are ready to begin writing actual code, there are a lot of technologies available to make your life easier. OS X supports all of the basic features such as memory management, file management, networking, and concurrency that you need to write your code. In some cases, though, OS X also provides more sophisticated services (or specific coding conventions) that, when followed, can make writing your code even easier.

当你准备好开始写代码时,有许多可用的技术,让你更轻松。OS X支持应用所需的所有基础特性,诸如内存管理、文件管理、网络、并发等。尽管如此,在有些情况下,OS X也提供了复杂的服务(或特殊的编码约定),使用它们会使编码工作更轻松。


Based on UNIX

基于UNIX

OS X is powered by a 64-bit Mach kernel, which manages processor resources, memory, and other low-level behaviors. On top of the kernel sits a modified version of the Berkeley Software Distribution (BSD) operating system, which provides interfaces that apps can use to interact with the lower-level system. This combination of Mach and BSD provides the following system-level support for your apps:

OS X基于64Mach内核之上,管理处理器、内存和其它底层行为。位于内核之上的是BSD操作系统的修改版本,提供了应用程序与底层操作系统的接口。MachBSD的结合,为应用提供了系统级的支撑:

  • Preemptive multitasking—All processes share the CPU efficiently. The kernel schedules processes in a way that ensures they all receive the time they need to run. Even background apps continue to receive CPU time to execute ongoing tasks.
  • 多任务优先——所有进程高效分享CPU。内核科学调度进程,确保每个进程都收到它运行所需的CPU时间。即使是后台应用,也会持续收到CPU时间,来完成它们的工作。
  • Protected memory—Each process runs in its own protected memory space, which prevents processes from accidentally interfering with each other. (Apps can share part of their memory space to implement fast interprocess communication but take responsibility for synchronizing and locking that memory appropriately.) 
  • 内存保护——每个进程在其自身受保护的内存空间中运行,防止进程之间相互干扰。(应用可以分享它们的部分内存来实现进程间的快速通信,但是要负责进行同步和锁定内存。)
  • Virtual memory—64-bit apps have a virtual address space of approximately 18 exabytes (18 billion billion bytes). (If you create a 32-bit app, the amount of virtual memory is only 4 GB.) When an app’s memory usage exceeds the amount of free physical memory, the system transparently writes pages to disk to make more room. Written out pages remain on disk until they are needed in memory again or the app exits.
  • 虚拟内存——64位应用可以拥有约18艾字节的虚拟地址空间18*10亿*10亿字节)。(如果是32位的应用,虚拟内存只有4 GB。)当应用所需的内存量超过了剩余物理内存量,系统会将内存页写入磁盘,来腾出更多空间。写入的内存页会留在磁盘上,直到内存需要或程序退出。
  • Networking and Bonjour—OS X provides support for the standard networking protocols and services in use today. BSD sockets provide the low-level communication mechanism for apps, but higher-level interfaces also exist. Bonjour simplifies the user networking experience by providing a dynamic way to advertise and connect to network services over TCP/IP. 
  • 网络和Bonjour——OS X提供了当前常用的基础网络协议和服务支持。BSD socket为应用提供了底层通信机制,同时也有高层接口。Bonjour通过提供动态广播和连接基于TCP/IP的网络服务,简化了用户的网络体验。

For detailed information about the underlying environment of OS X, seeKernel and Device Drivers Layer in Mac Technology Overview.

获取更多OS X底层环境的细节信息,参考Kernel and Device Drivers Layer in Mac Technology Overview.


Concurrency and Threading

并发和线程

Each process starts off with a single thread of execution and can create more threads as needed. Although you can create threads directly using POSIX and other higher-level interfaces, for most types of work it is better to create them indirectly using block objects with Grand Central Dispatch (GCD) or operation objects, a Cocoa concurrency technology implemented by the NSOperation class.

进程从一个执行的线程开始,可根据需要创建多个线程。尽管可以通过使用POSIX或其它高层接口创建线程,但对于大多数工作来说,更好的方式是使用Grand Central Dispatch (简称GCD,直译为统一中心分派,是苹果公司的一种多线程优化技术的块对象或operation对象来间接创建。operation对象是Cocoa的并发技术,通过NSOperation类实现。

GCD and operation objects are an alternative to raw threads that simplify or eliminate many of the problems normally associated with threaded programming, such as synchronization and locking. Specifically, they define an asynchronous programming model in which you specify only the work to be performed and the order in which you want it performed. The system then handles the tedious work required to schedule the necessary threads and execute your tasks as efficiently as possible on the current hardware. You should not use GCD or operations for work requiring time-sensitive data processing (such as audio or video playback), but you can use them for most other types of tasks.

GCDoperation对象可以相互替代,用于简化或避免多线程编程中出现的许多问题,如同步和锁。它们定义了一个异步的编程模型——在这个模型中,可以指定要完成的工作及其顺序。然后系统会接手那些冗长而单调的工作,在当前设备上调度必要的线程,尽可能高效地处理任务。不要使用GCDoperation对象处理那些对时间敏感的数据处理工作(比如音乐或者视频播放),但可以用它们完成其它的大多数工作。

For more information on using GCD and operation objects to implement concurrency in your apps, seeConcurrency Programming Guide.

了解使用GCDoperation对象在应用中实现并发操作的信息,参考Concurrency Programming Guide.


The File System

文件系统

The file system in OS X is structured to provide a better experience for users. Rather than exposing the entire file system to the user, the Finder hides any files and directories that an average user should not need to use, such as the contents of low-level UNIX directories. This is done to provide a simpler interface for the end user (and only in places like the Finder and the open and save panels). Apps can still access any files and directories for which they have valid permissions, regardless of whether they are hidden by the Finder. 

OS X中的文件系统是结构化的,旨在为用户提供更好的体验。相较于把整个文件系统展示给用户,Finder应用隐藏了那些普通用户不需要使用的文件和目录,比如底层的UNIX目录中的内容。这样做为终端用户提供了更为简洁的界面(仅在Finder和打开、保存对话框中使用)。只要有合法权限,应用仍然可以访问任何文件和目录,不管Finder是否隐藏了它们。

When creating apps, you should understand and follow the conventions associated with the OS X file system. Knowing where to put files and how to get information out of the file system ensures a better user experience. 

创建应用时,应当理解和遵循OS X文件系统的约定。了解将文件放置到哪里以及如何从文件系统获取信息,确保用户拥有更好的体验。


A Few Important App Directories

一些重要的应用目录

The OS X file system is organized in a way that groups related files and data together in specific places. Every file in the file system has its place and apps need to know where to put the files they create. This is especially important if you are distributing your app through the App Store, which expects you to put your app’s data files in specific directories. 

OS X文件系统中,相关的文件和数据是分组存放在特定位置的。文件系统中的每个文件都有它的位置,应用需要知道它所创建的文件应该放在哪里。当你需要通过App Store发布应用时,这一点尤为重要——它要求你把应用的数据文件放到特定的文件夹中。


Table 1-1 lists the directories with which apps commonly interact. Some of these directories are inside the home directory, which is either the user’s home directory or, if the app adopts App Sandbox, the app’s container directory as described in App Sandbox and XPC. Because the actual paths can differ based on these conditions, use theURLsForDirectory:inDomains: method of the NSFileManager class to retrieve the actual directory path. You can then add any custom directory and filename information to the returned URL object to complete the path.

1-1列出了应用经常需要打交道的文件夹。一些文件夹位于主文件夹中——可能是用户的主文件夹,如果应用使用应用沙箱,也可能是App Sandbox and XPC描述的应用的容器文件夹。由于不同情况下实际路径不同,所以需要使用NSFileManager类的URLsForDirectory:inDomains:方法来获取实际文件夹路径。从该方法获取的路径,再添加上自定义的文件夹或文件信息,就得到了完整的路径。


Table 1-1  Key directories for Mac apps

1-1 Mac应用程序主要文件夹

Directory

Description

Applications directory

应用程序文件夹

This is the installation directory for your app bundle. The path for the global Applications directory is/Applications but each user directory may have a local applications directory containing user-specific apps. Regardless, you should not need to use this path directly. To access resources inside your application bundle, use anNSBundle object instead.

这是应用包的安装文件夹。应用程序文件夹的全局路径是“/Applications”,不过,每个用户文件夹都拥有一个本地应用程序文件夹,用于存储用户特有的应用。无需直接使用这个文件夹。要访问应用包中的资源,可使用NSBundle对象。

For more information about the structure of your application bundle and how you locate resources, seeThe OS X Application Bundle.

关于应用包的结构以及如何定位资源,参考The OS X Application Bundle.

Home directory

主文件夹

The configuration of your app determines the location of the home directory seen by your app:

应用的配置决定了应用可见的主文件夹的位置:

  • For apps running in a sandbox in OS X v10.7 and later, the home directory is the app’s container directory. For more information about the container directory, seeThe Keychain.
  • 在OS X v10.7及其之后,应用在沙箱中运行,主文件夹就是应用的容器文件夹。更多容器文件夹的信息,参考The Keychain.
  • For apps running outside of a sandbox (including those running in versions of OS X before 10.7), the home directory is the user-specific subdirectory of/Users that contains the user’s files.
  • 在沙箱之外运行的应用(包括那些在OS X v10.7之前运行的应用),主文件夹是存储用户文件的“/Users”文件夹中的一个特定子文件夹。

To retrieve the path to the home directory, use the NSHomeDirectory function.

如需获得主文件夹的路径,使用NSHomeDirectory功能。

Library directory

库文件夹

The Library directory is the top-level directory for storing private app-related data and preferences. There are several Library directories scattered throughout the system but you should always use the one located inside the current home directory.

库文件夹是用于存放应用私有的数据和设置的顶层文件夹。系统中散布着多个库文件夹,但应用只能使用位于当前主文件夹中的那个库文件夹。

Do not store files directly at the top-level of the Library directory. Instead, store them in one of the specific subdirectories described in this table.

不要直接在顶层库文件夹中存放文件。替代方案是,把它们存放到这个表格中描述的特殊子文件夹中。

In OS X v10.7 and later, the Finder hides the Library directory in the user’s home folder by default. Therefore, you should never store files in this directory that you want the user to access.

在OS X v10.7及其之后,Finder默认隐藏用户主文件夹中的库文件夹。因此,不要把那些希望用户访问的文件放到这个文件夹中。

To get the path to this directory use the NSLibraryDirectory search path key with the NSUserDomainMask domain.

获取这个文件夹的路径,可在NSUserDomainMask域中使用路径查找键NSLibraryDirectory

Application Support directory

应用程序支持文件夹

The Application Support directory is where your app stores any type of file that supports the app but is not required for the app to run, such as document templates or configuration files. The files should be app-specific but should never store user data. This directory is located inside the Library directory.

应用程序支持文件夹用于存放支持应用、但非应用运行必须的任何文件,比如文档模板、配置文件等。这些文件是应用特有的,绝不能存放用户数据。这个文件夹位于库文件夹中。

Never store files at the top level of this directory: Always put them in a subdirectory named for your app or company.

不要在这个文件夹的顶层存放任何文件:把它们放到以你的应用或公司命名的子文件夹中。

If the resources apply to all users on the system, such as document templates, place them in/Library/Application Support. To get the path to this directory use theNSApplicationSupportDirectory search path key with the NSLocalDomainMask domain. If the resources are user-specific, such as workspace configuration files, place them in the current user’s~/Library/Application Support directory. To get the path to this directory use theNSApplicationSupportDirectory search path key with the NSUserDomainMask domain.

如果资源服务于系统中的所有用户,比如文档模板,那就把它们存放到“/Library/Application Support”中。获取这个文件夹的路径,可在NSLocalDomainMask域中使用路径查找键NSApplicationSupportDirectory。如果资源是用户特有的,比如工作区配置文件,那就把它们存放到当前用户的“~/Library/Application Support”中。获取这个文件夹的路径,可在NSUserDomainMask域中使用路径查找键NSApplicationSupportDirectory

Caches directory

缓存文件夹

The Caches directory is where you store cache files and other temporary data that your app can re-create as needed. This directory is located inside the Library directory.

缓存文件夹用于存放缓存文件和其它应用根据需要可重新生成的临时数据。这个文件夹位于库文件夹中。

Never store files at the top level of this directory: Always put them in a subdirectory named for your app or company. Your app is responsible for cleaning out cache data files when they are no longer needed. The system does not delete files from this directory.

不要在这个文件夹的顶层存放任何文件:把它们放到以你的应用或公司命名的子文件夹中。当不再需要缓存数据的时候,应用有义务清空缓存。系统不会清理这个文件夹。

To get the path to this directory use the NSCachesDirectory search path key with the NSUserDomainMask domain.

获取这个文件夹的路径,可在NSUserDomainMask域中使用路径查找键NSCachesDirectory

Movies directory

影片文件夹

The Movies directory contains the user’s video files.

影片文件夹用于存放用户的视频文件。

To get the path to this directory use the NSMoviesDirectory search path key with the NSUserDomainMask domain.

获取这个文件夹的路径,可在NSUserDomainMask域中使用路径查找键NSMoviesDirectory

Music directory

音乐文件夹

The Music directory contains the user’s music and audio files.

音乐文件夹用于存放用户的音乐和音频文件。

To get the path to this directory use the NSMusicDirectory search path key with the NSUserDomainMask domain.

获取这个文件夹的路径,可在NSUserDomainMask域中使用路径查找键NSMusicDirectory

Pictures directory

图片文件夹

The Pictures directory contains the user’s images and photos.

图片文件夹用于存放用户的图像和照片。

To get the path to this directory use the NSPicturesDirectory search path key with the NSUserDomainMask domain.

获取这个文件夹的路径,可在NSUserDomainMask域中使用路径查找键NSPicturesDirectory

Temporary directory

临时文件夹

The Temporary directory is where you store files that do not need to persist between launches of your app. You normally use this directory for scratch files or other types of short-lived data files that are not related to your app’s persistent data. This directory is typically hidden from the user.

临时文件夹用于存放不需要持久化的数据。通常使用这个文件夹来存放文件草稿或其它与应用持久化存储无关的短期数据文件。这个文件夹对用户隐藏。

Your app should remove files from this directory as soon as it is done with them. The system may also purge lingering files from this directory at system startup.

当文件不再需要时,应当从这个文件夹中移除。系统启动时,可能会清理这个文件夹中的剩余文件。

To get the path to this directory use the NSTemporaryDirectory function.

获取这个文件夹的路径,使用NSTemporaryDirectory方法。

Listing 1-1 shows an example of how to retrieve the base path to theApplication Support directory and then append a custom app directory to it.

代码1-1 展示了一个获取应用程序支持文件夹路径并添加自定义应用目录的示例。

Listing 1-1  Getting the path to the Application Support directory

NSFileManager* fileManager = [NSFileManager defaultManager];


NSURL* appSupportDir = nil;




NSArray *urls = [fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];


if ([paths count] > 0) {


   appSupportDir = [[urls objectAtIndex:0] URLByAppendingPathComponent:@"com.example.MyApp"];


}


For more information about how to access files in well known system directories, seeFile System Programming Guide.

有关访问系统常用文件夹中文件的方法信息,参考 File System Programming Guide.


Coordinating File Access with Other Processes

与其它进程协调文件访问

In OS X, other processes may have access to the same files that your app does. Therefore, when working with files, you should use the file coordination interfaces introduced in OS X v10.7 to be notified when other processes (including the Finder) attempt to read or modify files your app is currently using. For example, coordinating file access is critical when your app adopts iCloud storage.

OS X中,其它进程也有可能访问你要访问的文件。因此,当处理文件时,要使用OS X v10.7引入的文件协调接口,以便在其它进程(包括Finder)试图读取或修改你正在使用的文件时,你的应用能够得到系统的通知。例如,当你使用iCloud存储时,协调文件访问尤为关键。

The file coordination APIs allow you to assert ownership over files and directories that your app cares about. Any time another process attempts to touch one of those items, your app is given a chance to respond. For example, when an app attempts to read the contents of a document your app is editing, you can write unsaved changes to disk before the other process is allowed to do its reading.

文件协调API允许你对关心的文件或文件夹声明所有权。不管任何时间,只要有其它进程试图接触这些项目,你的应用就会得到一次响应的机会。比如,当另外一个应用试图读取你的应用正在编辑的文档时,你可以先把未保存的修改写入磁盘,再允许其它进程来读取。

Using iCloud document storage, for example, you must incorporate file coordination because multiple apps can access your document files in iCloud. The simplest way to incorporate file coordination into your app is to use theNSDocument class, which handles all of the file-related management for you. SeeDocument-Based App Programming Guide for Mac.

当使用iCloud文件存储时,必须整合文件协调技术,因为许多应用都可以访问iCloud中的文件。为应用整合文件协调最简单的方式是使用NSDocument类,它可以进行所有文件相关的管理。参考Document-Based App Programming Guide for Mac.

On the other hand, if you're writing a library-style (or “shoebox”) app, you must use the file coordination interfaces directly, as described inFile System Programming Guide.

另一方面,如果你编写库(或者“鞋盒”)应用,则必须直接使用文件协调接口,可参见File System Programming Guide中的描述。


Interacting with the File System

与文件系统交互

Disks in Macintosh computers are formatted using the HFS+ file system by default. However, Macintosh computers can interact with disks that use other formats so you should never code specifically to any one file system. Table 1-2 lists some of the basic file system attributes you may need to consider in your app and how you should handle them.

苹果计算机默认使用HFS+文件系统来格式化磁盘。然而,苹果计算机可以与其它格式的磁盘进行交互,所以不要针对特定文件系统进行编码。表1-2列出了应用中需要考虑的基本文件系统特性,以及如何处理它们。

Table 1-2  Attributes for the OS X file system

1-2 OS X文件系统特性

Attribute 

Description

Case sensitivity

大小写敏感

The HFS+ file system is case-insensitive but also case-preserving. Therefore, when specifying filenames and directories in your code, it is best to assume case-sensitivity.

HFS+文件系统对大小写不敏感,但它保留大小写。因此,在处理文件名称时,最好考虑大小写因素。

Path construction

路径构造

Construct paths using the methods of the NSURL and NSString classes. The NSURL class is preferred for path construction because of its ability to specify not only paths in the local file system but paths to network resources.

使用NSURLNSString类的方法来构造路径。更推荐使用NSURL类来构造路径,因为它既能表示本地文件路径,又能表示网络资源路径。

File attributes

文件属性

Many file-related attributes can be retrieved using the getResourceValue:forKey:error: method of the NSURL class. You can also use anNSFileManager object to retrieve many file-related attributes.

NSURL类的getResourceValue:forKey:error:方法可以获取许多文件相关的属性。也可以使用NSFileManager对象来获取。

File permissions

文件权限

File permissions are managed using access control lists (ACLs) and BSD permissions. The system uses ACLs whenever possible to specify precise permissions for files and directories, but it falls back to using BSD permissions when no ACLs are specified.

文件权限受控于访问控制列表(ACLs) BSD权限。如果可能,系统会优先使用ACLs来明确文件和文件夹权限,但如果没有明确的ACLs,系统会退回使用BSD权限。

By default, any files your app creates are owned by the current user and given appropriate permissions. Thus, your app should always be able to read and write files it creates explicitly. In addition, the app’s sandbox may allow it to access other files in specific situations. For more information about the sandbox, see App Sandbox and XPC.

通常情况下,你的应用创建的所有文件都归当前用户所有,并由当前用户授予合适的权限。然而,应用应当总是可以读取和写入它自身创建的文件。另外,在特定的情况下,应用沙盒也可能允许它访问其它文件。关于沙盒的更多信息,参考App Sandbox and XPC.

Tracking file changes

跟踪文件变动

Apps that cannot use the File Coordination interfaces (see Coordinating File Access with Other Processes) to track changes to files and directories can use the FSEvents API instead. This API provides a lower-level interface for tracking file system interactions and is available in OS X v10.5 and later.

那些不能使用文件协调接口(参考Coordinating File Access with Other Processes)来跟踪文件和文件夹变化的应用,可以使用FSEvents API来代替。这个API提供了跟踪文件系统变化的底层接口,在OS X v10.5及其之后可用。

For information on how to use the FSEvents API, see File System Events Programming Guide.

关于如何使用FSEvents API,参考File System Events Programming Guide.


File-System Usage Requirements for the Mac App Store

Mac App Store文件系统使用要求

To promote a more consistent user experience, applications submitted to the Mac App Store must follow certain rules about where they write files. Users can be confused when applications cause unexpected side effects on the file system (for example, storing databases in the user’s Documents folder, storing files in the user’s Library folder that are not recognizably associated with your application, storing user data in the user’s Library folder, and so on).

为促进用户体验的一致性,提交到Mac App Store的应用在文件写入位置上,必须遵循特定的准则。应用如果在文件系统使用上“搞事情”(比如,把数据库文件存储到用户文档目录、把文件存储到无法与你的应用建立关联的用户库文件夹中、把用户数据存储到库文件夹中,等等),会困惑用户。

Your application must adhere to the following requirements:

应用必须遵循如下要求:

  • You may use Apple frameworks such as User Defaults, Calendar Store, and Address Book that implicitly write to files in specific locations, including locations your application is not allowed to access directly.
  • 可以使用诸如User DefaultsCalendar StoreAddress Book等苹果框架,虽然它们会隐式地将文件写入到特定位置;还可使用应用无法直接访问的位置信息。
  • Your application may write to temporary paths that you acquire using the appropriate Apple programming interfaces, such as theNSTemporaryDirectory function.
  • 使用诸如NSTemporaryDirectory功能等合适的苹果编程接口获得的临时文件夹,可以写入文件。
  • Your application may write to the following directories:
  • 你的应用可以写入到下列文件夹中:
    • ~/Library/Application Support/<app-identifier>
    • ~/Library/<app-identifier>
    • ~/Library/Caches/<app-identifier>
  • where <app-identifier> is your application's bundle identifier, its name, or your company’s name. This must exactly match what is in iTunes Connect for the application.Always use Apple programming interfaces such as theURLsForDirectory:inDomains: function to locate these paths rather than hardcoding them. For more information, seeFile System Programming Guide.
  • <app-identifier>可以是你的应用ID、应用名称或者你的公司名称。这些必须与应用在iTunes Connect中的信息匹配。应当使用诸如URLsForDirectory:inDomains:方法等苹果编程接口来定位路径,而不应进行硬编码。更多信息,参考File System Programming Guide.
  • If your application manages libraries of pictures, music, or movies, the application may also write to the following directories:
  • 如果应用管理图片、音乐或影片,也可以写入下列目录:
    • ~/Pictures/<app-identifier>
    • ~/Music/<app-identifier>
    • ~/Movies/<app-identifier>
  • If the user explicitly chooses to save data in an alternate location (using a Save As dialog), your application may write to the chosen location.
  • 如果用户明确指定了数据存储位置(比如使用存储为对话框),应用可以写入到用户指定位置。


Security

安全

The security technologies in OS X help you safeguard sensitive data created or managed by your app, and help minimize damage caused by successful attacks from hostile code. These technologies impact how your app interacts with system resources and the file system.

OS X中的安全技术帮助你保护应用生成或管理的敏感数据,并将由恶意代码攻击造成的损害降到最低。这些技术将对应用与系统资源和文件系统的交互产生影响。


App Sandbox and XPC

应用沙盒和XPC

You secure your app against attack from malware by following the practices recommended inSecure Coding Guide. But an attacker needs only to find a single hole in your defenses, or in any of the frameworks and libraries that you link against, to gain control of your app along with all of its privileges.

遵从Secure Coding Guide推荐的实践,可以保护应用免受恶意软件的攻击。但攻击者只需找到你应用防御措施或是应用链接的框架和库中的一个漏洞,就可以控制你的应用及其所拥有的权限。

App Sandbox provides a last line of defense against stolen, corrupted, or deleted user data if malicious code exploits your app. App Sandbox also minimizes the damage from coding errors. Its strategy is twofold:

如果恶意代码利用你的应用,那么应用沙箱可以提供最后一道防线,防止用户数据被盗、丢失或者删除。应用沙箱也可以最大限度地降低错误代码的损害。它的战略有两个方面:

  1. App Sandbox enables you to describe how your app interacts with the system. The system then grants your app the access it needs to get its job done, and no more. For your app to provide the highest level of damage containment, the best practice is to adopt the tightest sandbox possible.
  2. 沙箱允许你定义你的应用如何与系统交互。然后系统仅向应用授予完成工作所需要的最低权限。应用若想提供最高级别的损害控制,最好的实践就是尽可地收紧沙箱。
  3. App Sandbox allows the user to transparently grant your app additional access by way of Open and Save dialogs, drag and drop, and other familiar user interactions.

沙箱允许用户为应用显式地授予额外的权利,可通过打开和保存对话框、拖放及其它用户熟悉的交互方式进行。

You describe your app’s interaction with the system by way of setting entitlements in Xcode. An entitlement is a key-value pair, defined in aproperty list file, that confers a specific capability or security permission to a target. For example, there are entitlement keys to indicate that your app needs access to the camera, the network, and user data such as the Address Book. For details on all the entitlements available in OS X, seeEntitlement Key Reference.

描述应用与系统交互方式的方法是在Xcode中设置权限。权限是一个键-值对,在属性列表文件中定义,可对目标授予特殊能力或安全权限。比如,应用访问摄像头、网络或地址薄等用户数据,都有相应的权限键。OS X中所有可用的权限细节,参考Entitlement Key Reference.

When you adopt App Sandbox, the system provides a special directory for use by your app—and only by your app—called a container. Your app has unfettered read/write access to the container. All OS X path-finding APIs, above the POSIX layer, are relative to the container instead of to the user’s home directory. Other sandboxed apps have no access to your app’s container, as described further inCode Signing.

使用沙箱后,系统会为应用提供一个特殊的文件夹——仅供你的应用使用——这个文件夹叫做容器。应用对容器有自由读写权限。OS X所有的路径查找API,在POSIX层之上,都是与容器关联,而不是与用户主文件夹关联。其它沙箱应用无权访问你的应用容器,正如下文中Code Signing所描述的那样。


iOS Note: Because it is not for user documents, an OS X container differs from an iOS container which, in iOS, is the one and only location for user documents. As the sole local location for user documents, an iOS container is usually known simply as an app’s Documents directory.

iOS 贴示: 由于OS X容器不是用于用户文档,OS X容器与iOS容器不同,iOS容器是存储用户文档有且仅有的一个位置。由于iOS容器是用户文档的唯一存储位置,所以它通常被简单地当做应用的文档文件夹。

In addition, an iOS container contains the app itself. This is not so in OS X.

另外,iOS容器包含应用自身。在OS X中就不是这样。


iCloud Note: Apple’s iCloud technology, as described in iCloud Storage, uses the name “container” as well. There is no functional connection between an iCloud container and an App Sandbox container.

iCloud 贴示:被称之为iCloud存储的苹果的iCloud技术,同样也使用“容器”这个名字。但iCloud容器和应用沙盒容器没有功能上的联系。


Your sandboxed app can access paths outside of its container in the following three ways:

应用可通过以下三种方式来访问容器之外的路径:

  • At the specific direction of the user
  • 用户指定
  • By you configuring your app with entitlements for specific file-system locations, such as the Movies folder
  • 配置应用,赋予其访问特殊系统位置的权限,比如影片文件夹
  • When a path is in any of certain directories that are world readable
  • 当路径位于全局可读的特定文件夹中

The OS X security technology that interacts with the user to expand your sandbox is called Powerbox. Powerbox has no API. Your app uses Powerbox transparently when, for example, you use theNSOpenPanel and NSSavePanel classes, or when the user employs drag and drop with your app.

通过用户扩展沙箱的OS X安全技术称作PowerboxPowerbox没有API。当使用NSOpenPanelNSSavePanel类,或当用户拖放项目时,应用显式地使用Powerbox

Some app operations are more likely to be targets of malicious exploitation. Examples are the parsing of data received over a network, and the decoding of video frames. By using XPC, you can improve the effectiveness of the damage containment offered by App Sandbox by separating such potentially dangerous activities into their own address spaces.

一些应用行为容易成为恶意攻击的目标。这样的例子有解析从网络获取的数据、视频帧解码等。使用XPC,通过将潜在的危险行为分离到它们自己的地址空间,可以提升应用沙箱提供的损害控制的有效性。

XPC is an OS X interprocess communication technology that complements App Sandbox by enabling privilege separation. Privilege separation, in turn, is adevelopment strategy in which you divide an app into pieces according to the system resource access that each piece needs. The component pieces that you create are called XPC services. For details on adopting XPC, seeDaemons and Services Programming Guide.

XPC是一项OS X进程间通信的技术,通过允许特权分离,作为应用沙箱的补充。反过来,特权分离是一个发展战略,你可以把应用划分成若干“部件”——依据每个“部件”对系统资源的访问需求来划分。这些你创建的“部件”称作XPC服务。关于适配XPC的细节,参考Daemons and Services Programming Guide.

For a complete explanation of App Sandbox and how to use it, read App Sandbox Design Guide.

关于沙箱的完整解释及使用方法,参考 App Sandbox Design Guide.


Code Signing

代码签名

OS X employs the security technology known as code signing to allow you to certify that your app was indeed created by you. After an app is code signed, the system can detect any change to the app—whether the change is introduced accidentally or by malicious code. Various security technologies, including App Sandbox and parental controls, depend on code signing.

OS X使用称作代码签名的安全技术,允许你来确认应用确实是你所创建的。当应用进行代码签名后,系统会检测该应用的任何变动——不管该变动是意外发生的,还是恶意代码导致的。包括沙箱和家长控制在内的多项安全技术,都依赖于代码签名。

In most cases, you can rely on Xcode’s automatic code signing, which requires only that you specify a code signing identity in the build settings for your project. The steps to take are described in Code Signing Your App in Tools Workflow Guide for Mac. If you need to incorporate code signing into an automated build system, or if you link your app against third-party frameworks, refer to the procedures described inCode Signing Guide.

在大多数情况下,可以依靠Xcode的自动代码签名,它所需要你做的工作的仅仅是在工程的Build Settings中明确代码签名标识。所需步骤可参照Tools Workflow Guide for Mac中的Code Signing Your App部分。如果你需要将代码签名整合到自动编译系统,或者是将你的应用链接到第三方框架,参考Code Signing Guide中描述的步骤。

When you adopt App Sandbox, you must code sign your app. This is because entitlements (including the special entitlement that enables App Sandbox) are built into an app’s code signature.

如需使用应用沙箱,则必须进行代码签名。这是由于权限(包括允许应用沙箱的权限)会被编译到应用的代码签名中去。

OS X enforces a tie between an app’s container and the app’s code signature. This important security feature ensures that no other sandboxed app can access your container. The mechanism works as follows: After the system creates a container for an app, each time an app with the same bundle ID launches, the system checks that the app’s code signature matches a code signature expected by the container. If the system detects a mismatch, it prevents the app from launching.

OS X在应用容器和应用代码签名之间有强制连接。这个重要的安全特性,确保了其它沙箱应用无法访问你的应用容器。这个机制的工作方式如下:在系统为应用创建了沙箱之后 ,每次一个拥有相同包ID的应用启动时,系统会检查这个应用的代码签名是否与容器期望的代码签名相匹配。如果系统发现不匹配,它将阻止应用启动。

For a complete explanation of code signing in the context of App Sandbox, readApp Sandbox in Depth in App Sandbox Design Guide.

关于应用沙箱环境中代码签名的完整阐释,参阅App Sandbox in DepthApp Sandbox Design Guide.


The Keychain

钥匙串

A keychain is a secure, encrypted container for storing a user’s passwords and other secrets. It is designed to help a user manage their multiple logins, each with its own ID and password. You should always use keychain to store sensitive credentials for your app.

钥匙串是一个安全、加密的容器,用于存储用户的密码和其它秘密。它的设计宗旨是帮助用户管理众多的登录信息,每条登录信息都有自己的ID和密码。应当总是使用钥匙串来为应用存储敏感的证书。

For more on the keychain, see Keychain Services Concepts in Keychain Services Programming Guide.

关于更多钥匙串的信息,参考Keychain Services Programming Guide中的Keychain Services Concepts.


原文摘自苹果官网,译文为原创,请勿转载。 译文不断更新中,欢迎关注。 水平有限,译文有错误、疏漏之处,敬请指正。
知识有价,感谢您支持原创,微信扫码赞助

邮箱:johnbob2014@icloud.com
微信公众号CocoaLover,扫码关注:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值