天天看點

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. 

Mac應用程式設計指南之二——Mac應用程式環境

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.
  • 考慮減少或排除使用者與檔案系統的互動。與其通過打開和儲存對話框向使用者展示整個檔案系統,一些應用采取類似iPhoto和iTunes的方式,專門設計了适合應用内容的簡易浏覽器來向使用者展示,進而提供了更好的體驗。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.
  • 使用動畫來提供回報、傳遞資訊。在AppKit和Core 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基于64位Mach核心之上,管理處理器、記憶體和其它底層行為。位于核心之上的是BSD作業系統的修改版本,提供了應用程式與底層作業系統的接口。Mach和BSD的結合,為應用提供了系統級的支撐:

  • 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.

GCD和operation對象可以互相替代,用于簡化或避免多線程程式設計中出現的許多問題,如同步和鎖。它們定義了一個異步的程式設計模型——在這個模型中,可以指定要完成的工作及其順序。然後系統會接手那些冗長而單調的工作,在目前裝置上排程必要的線程,盡可能高效地處理任務。不要使用GCD和operation對象處理那些對時間敏感的資料處理工作(比如音樂或者視訊播放),但可以用它們完成其它的大多數工作。

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

了解使用GCD和operation對象在應用中實作并發操作的資訊,參考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.

使用NSURL和NSString類的方法來構造路徑。更推薦使用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 Defaults、Calendar Store和Address 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安全技術稱作Powerbox。Powerbox沒有API。當使用NSOpenPanel和NSSavePanel類,或當使用者拖放項目時,應用顯式地使用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 Depth和App 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.

原文摘自蘋果官網,譯文為原創,請勿轉載。 譯文不斷更新中,歡迎關注。 水準有限,譯文有錯誤、疏漏之處,敬請指正。 知識有價,感謝您支援原創,微信掃碼贊助:

Mac應用程式設計指南之二——Mac應用程式環境

郵箱:[email protected] 微信公衆号CocoaLover,掃碼關注:

Mac應用程式設計指南之二——Mac應用程式環境

繼續閱讀