File System Programming --- (二)

File System Basics

The file systems in OS X and iOS handle the persistent storage of data files, apps, and the files associated with the operating system itself. Therefore, the file system is one of the fundamental resources used by all processes.html

OS X 和 iOS的文件系統處理數據文件,應用程序以及跟操做系統自身相關的各類文件的永久保存。 所以,文件系統是全部進程都須要使用的基礎資源之一。web

The file systems in OS X and iOS are both based on the UNIX file system. All of the disks attached to the computer—whether they are physically plugged into the computer or are connected indirectly through the network—contribute space to create a single collection of files. Because the number of files can easily be many millions, the file system uses directories to create a hierarchical organization. Although the basic directory structures are similar for iOS and OS X, there are differences in the way each system organizes apps and user data.數據庫

OS X 和 iOS 的文件系統都是基於UNIX 文件系統之上的。 全部鏈接到電腦的磁盤--不管它們是物理插入電腦仍是經過網絡間接鏈接到電腦--,全部磁盤都用空間建立一個單一的文件集合。 由於文件數量很容易就能達到幾百萬,文件系統使用目錄來建立一個層次組織。 儘管基本目錄結構跟iOS 和 OS X 類似,可是在每一個系統組織應用程序和用戶數據方面存在區別。緩存

Before you begin writing code that interacts with the file system, you should first understand a little about the organization of file system and the rules that apply to your code. Aside from the basic tenet that you cannot write files to directories for which you do not have appropriate security privileges, apps are also expected to be good citizens and put files in appropriate places. Precisely where you put files depends on the platform, but the overarching goal is to make sure that the user’s files remain easily discoverable and that the files your code uses internally are kept out of the user’s way.安全

在你開始編寫跟文件系統交互的代碼以前,你應該首先了解一些文件系統組織以及應用於你的代碼的各類規則。 除了遵循你不能把文件寫入你沒有權限的目錄這基本原則以外,應用程序也指望把文件放入一個適當的地方。 準確地說文件放在哪裏取決於平臺,可是首要目標是確保用戶文件能被簡單發現而且內部代碼將不以用戶方式保存。服務器

About the iOS File System

1、關於iOS文件系統網絡

The iOS file system is geared toward apps running on their own. To keep the system simple, users of iOS devices do not have direct access to the file system and apps are expected to follow this convention.併發

iOS 文件系統面向應用程序運行它們本身的系統。 爲了保持系統的簡單性, iOS設備的用戶不能直接訪問文件系統,應用程序須要遵照如下約定。app

Every App Is an Island

一、每一個應用程序都是一個島嶼框架

An iOS app’s interactions with the file system are limited mostly to the directories inside the app’s sandbox. During installation of a new app, the installer code creates a home directory for the app, places the app in that directory, and creates several other key directories. These directories constitute the app’s primary view of the file system. Figure 1-1 shows a representation of the sandbox for an app.

一個iOS應用程序跟文件系統的交互都主要限於應用程序沙盒內的目錄。 當一個新應用程序被安裝時,安裝代碼爲應用程序建立一個主目錄, 把應用程序放在該主目錄,並建立一些其它主要目錄。 這些目錄組成應用程序文件系統的主要視圖。圖1-1顯示了一個表明性的應用程序沙盒。

Figure 1-1  Each iOS app operates within its own sandbox

圖 1-1 每一個iOS 應用程序都在它本身的沙盒裏操做

Because it is in a sandbox, an app is generally prohibited from accessing or creating files in directories outside of its home directory. One exception to this rule occurs when an app uses public system interfaces to access things such as the user’s contacts or music. In those cases, the system frameworks handle any file-related operations needed to read from or modify the appropriate data stores.

由於這是在一個沙盒內,因此應用程序通常禁止在其主目錄外訪問或建立文件。 該規則的一個例外是當應用程序使用公共系統接口來訪問東西時,好比用戶的聯絡或音樂。 在這些狀況下,系統框架處理任何文件相關的操做都須要讀取相應的數據存儲或修改它。

For a detailed look at the directories inside an app’s sandbox, see 「iOS Standard Directories: Where Files Reside」

關於一個應用程序沙盒內目錄的詳情,請看「iOS Standard Directories: Where Files Reside」

iOS Standard Directories: Where Files Reside

二、iOS 標準目錄:文件所在

For security purposes, an iOS app has limited a number of places where it can write its data. When an app is installed on a device, iTunes creates a home directory for the app. This directory represents the universe for that app and contains everything the app can access directly. Table 1-1 lists some of the important subdirectories of this home directory and describes their intended usage. This table also describes any additional access restrictions for each subdirectory and points out whether the directory’s contents are backed up by iTunes.

爲了安全目的,iOS應用程序限定了一些它能寫入數據的地方。當應用程序被安裝到一個設備時,iTunes 爲應用程序建立了一個主目錄。 該主目錄表明了那個應用程序的所有,包含了應用程序能直接訪問的全部東西。 表 1-1 列出了一些該主目錄的重要子目錄並描述了它們的用途。 該表格還描述了每一個子目錄的所有額外訪問限制,並指出目錄的內容是否被iTunes備份。

Table 1-1  Commonly used directories of an iOS app表 1-1 iOS應用程序的經常使用目錄

Directory

Description

<Application_Home>/AppName.app

This is the bundle directory containing the app itself. Do not write anything to this directory. To prevent tampering, the bundle directory is signed at installation time. Writing to this directory changes the signature and prevents your app from launching again.

這是包含應用程序自身的束目錄。不要往該目錄寫入任何東西。爲了阻止被篡改,該目錄在安裝時被簽名。往該目錄寫入數據將改變了簽名,應用程序將沒法再啓動。

In iOS 2.1 and later, the contents of this directory are not backed up by iTunes. However, iTunes does perform an initial sync of any apps purchased from the App Store.

在iOS 2.1 以及之後版本,該目錄的內容沒有被iTunes備份。 然而,iTunes 確實對任何從App Store 購買的應用程序作一個初始化同步。

<Application_Home>/Documents/

Use this directory to store critical user documents and app data files. Critical data is any data that cannot be recreated by your app, such as user-generated content.

使用該目錄來存儲關鍵的用戶文檔以及應用程序數據文件。關鍵數據是指應用程序不能再次建立的數據, 好比用戶生成的內容。

The contents of this directory can be made available to the user through file sharing. The contents of this directory are backed up by iTunes.

該目錄的內容可經過文件共享提供給用戶。該目錄的內容由iTunes備份。

<Application_Home>/Documents/Inbox

Use this directory to access files that your app was asked to open by outside entities. Specifically, the Mail program places email attachments associated with your app in this directory; document interaction controllers may also place files in it.

使用該目錄來訪問由外部實體請求應用程序打開的各類文件。特別是,郵箱程序在該程序裏放置應用程序相關的郵件附件;跟控制器交互的文檔也可能在這裏存儲文件。

Your app can read and delete files in this directory but cannot create new files or write to existing files. If the user tries to edit a file in this directory, your app must silently move it out of the directory before making any changes.

你的應用程序能在該目錄裏讀取或刪除文件,可是不能建立新文件或向已有的文件裏寫入數據。若是用戶嘗試着在該目錄裏編輯一個文件,應用程序必須在對文件作任何改變以前悄悄地把文件移到目錄外。

The contents of this directory are backed up by iTunes.

該目錄的內容由iTunes備份。

<Application_Home>/Library/

This directory is the top-level directory for files that are not user data files. You typically put files in one of several standard subdirectories but you can also create custom subdirectories for files you want backed up but not exposed to the user. You should not use this directory for user data files.

該目錄是文件的頂層目錄,它不包含用戶數據文件。 你一般能夠在這些標準子目錄裏放置文件,可是你也能夠爲不想暴露給用戶的文件建立自定義子目錄。你不該該使用該目錄來存儲用戶數據文件。

The contents of this directory (with the exception of the Cachessubdirectory) are backed up by iTunes.

該目錄的內容由iTunes備份,Caches 子目錄除外。

For additional information about the Library directory, see 「The Library Directory Stores App-Specific Files.」

關於Library 目錄的額外信息,請看 「The Library Directory Stores App-Specific Files.」

<Application_Home>/tmp/

Use this directory to write temporary files that do not need to persist between launches of your app. Your app should remove files from this directory when it determines they are no longer needed. (The system may also purge lingering files from this directory when your app is not running.)

使用該目錄存儲臨時文件,這些文件不須要在應用程序啓動期間長期保持。當應用程序肯定這些文件不被須要時,它應該從該目錄刪除這些文件。(當應用程序中止運行時,該系統還可能從該目錄清除頑固文件。)

In iOS 2.1 and later, the contents of this directory are not backed up by iTunes.

從iOS 2.1 以及以後版本,該目錄的內容不被iTunes備份。

An iOS app may create additional directories in the DocumentsLibrary, and tmpdirectories. You might want to do this to organize the files in those locations better.

iOS 應用程序可能在Documents, Library, 以及 tmp 目錄裏建立額外的目錄。 你可能想這樣作在那些地方更好的組織文件。

For information about how to get references to the preceding directories from your iOS app, see 「Locating Items in the Standard Directories.」 For tips on where to put files, see 「Where You Should Put Your App’s Files.」

關於如何從iOS應用程序得到前目錄的引用, 請看「Locating Items in the Standard Directories.」  關於在哪放置文件,請看「Where You Should Put Your App’s Files.」

Where You Should Put Your App’s Files

三、你應該在哪放置你的應用程序文件

To prevent the syncing and backup processes on iOS devices from taking a long time, be selective about where you place files inside your app’s home directory. Apps that store large files can slow down the process of backing up to iTunes or iCloud. These apps can also consume a large amount of a user's available storage, which may encourage the user to delete the app or disable backup of that app's data to iCloud. With this in mind, you should store app data according to the following guidelines:

爲防止在iOS設備花長時間同步和備份進程,在應用程序主目錄裏有選擇的放置你的文件。存儲大文件的應用程序會減慢備份到iTunes 或 iCloud的進程。這些應用程序還會消耗大量用戶的可用存儲,這樣可能會鼓勵用戶刪除應用程序或不容許備份該應用程序數據到iCloud。因此,你應該遵循如下指導原則來存儲應用程序數據:

  • Put user data in the <Application_Home>/Documents/. User data is any data that cannot be recreated by your app, such as user documents and other user-generated content.

    把用戶數據存在<Application_Home>/Documents/目錄。用戶數據是應用程序不能再次建立的全部數據,好比用戶文檔以及其它用戶相關的內容。

  • Handle support files—files your application downloads or generates and can recreate as needed—in one of two ways:

    用如下兩種方式之一來處理支持文件----應用程序下載或生產的文件並能根據須要再次建立。

    • In iOS 5.0 and earlier, put support files in the<Application_Home>/Library/Caches directory to prevent them from being backed up

      在iOS 5.0 以及早期版本中,把支持文件放在 <Application_Home>/Library/Caches 目錄裏,以阻止它們被備份。

    • In iOS 5.0.1 and later, put support files in the<Application_Home>/Library/Application Support directory and apply the com.apple.MobileBackup extended attribute to them. This attribute prevents the files from being backed up to iTunes or iCloud. If you have a large number of support files, you may store them in a custom subdirectory and apply the extended attribute to just the directory.

      在iOS 5.0.1 以及之後版本中,把支持文件放在 <Application_Home>/Library/Application Support 目錄並給它們提供 com.apple.MobileBackup 擴展屬性。該屬性阻止文件備份到iTunes 或 iCloud。 若是你有不少支持文件,你能夠把它們存儲在一個自定義子目錄並把擴展屬性應用給該目錄。

  • Put data cache files in the <Application_Home>/Library/Caches directory. Examples of files you should put in this directory include (but are not limited to) database cache files and downloadable content, such as that used by magazine, newspaper, and map apps. Your app should be able to gracefully handle situations where cached data is deleted by the system to free up disk space.

    把數據緩存文件放置在<Application_Home>/Library/Caches 目錄。 你應該放在該目錄的文件包括(但不只限於)數據庫緩存文件以及可下載的內容,好比雜誌,新聞以及地圖應用程序使用的內容。應用程序應該能優雅地處理緩存數據被系統刪除以釋放磁盤空間的各類狀況。

  • Put temporary data in the <Application_Home>/tmp directory. Temporary data comprises any data that you do not need to persist for an extended period of time. Remember to delete those files when you are done with them so that they do not continue to consume space on the user’s device.

    把臨時數據放置在<Application_Home>/tmp 目錄。 臨時數據包含你不須要持久保存一段時間的各類數據。 記住當你不須要它們時,請刪除這些文件,這樣它們就不會繼續佔用用戶設備的內存。

About the OS X File System

The OS X file system is designed for Macintosh computers, where both users and software have access to the file system. Users access the file system directly through the Finder, which presents a user-oriented view of the file system by hiding or renaming some files and directories. Apps access the file system using the system interfaces, which show the complete file system precisely as it appears on disk.

Domains Determine the Placement of Files

In OS X, the file system is divided into multiple domains, which separate files and resources based on their intended usage. This separation provides simplicity for the user, who only needs to worry about a specific subset of files. Arranging files by domain also lets the system apply blanket access privileges to files in that domain, preventing unauthorized users from changing files intentionally or inadvertently.

  • The user domain contains resources specific to the users who log in to the system. Although it technically encompasses all users, this domain reflects only the home directory of the current user at runtime. User home directories can reside on the computer’s boot volume (in the /Users directory) or on a network volume. Each user (regardless of privileges) has access to and control over the files in his or her own home directory.

     

  • The local domain contains resources such as apps that are local to the current computer and shared among all users of that computer. The local domain does not correspond to a single physical directory, but instead consists of several directories on the local boot (and root) volume. This domain is typically managed by the system, but users with administrative privileges may add, remove, or modify items in this domain.

     

  • The network domain contains resources such as apps and documents that are shared among all users of a local area network. Items in this domain are typically located on network file servers and are under the control of a network administrator.

     

  • The system domain contains the system software installed by Apple. The resources in the system domain are required by the system to run. Users cannot add, remove, or alter items in this domain.

     

Figure 1-2 shows how the local, system, and user domains map to the local file system of an OS X installation. (The network domain is not shown but is similar in many ways to the local domain.) This figure shows the visible directories that the user might see. Depending on the user’s system, other directories may be visible or some of the ones shown here may be hidden.

Figure 1-2  The local OS X file system

For information about the contents of the directories in OS X, see 「OS X Standard Directories: Where Files Reside.」 For information about the directories that OS X normally hides from the user (and why), see 「Hidden Files and Directories: Simplifying the User Experience.」

OS X Standard Directories: Where Files Reside

Whether provided by the system or created by your app, every file has its place in OS X. Table 1-2 lists some of the top-level directories in an OS X installation and the types of content that each one contains.

Table 1-2  Commonly used directories in OS X

Directory

Usage

/Applications

This directory is where you install apps intended for use by all users of a computer. The App Store installs apps purchased by the user in this directory automatically.

The Utilities subdirectory contains a subset of apps that are intended for use in managing the local system.

This directory is part of the local domain.

/Developer

This directory contains the Xcode apps, tools, and developer-related resources.

The default name of this directory is Developer but the user may change that name. A common reason to change the name is to support multiple installations of the Xcode tools. Regardless of the name, this directory is part of the local domain.

Library

There are multiple Library directories on the system, each one associated with a different domain or specific user. Apps should use the Library directory to store app-specific (or system-specific) resources.

For detailed information about the contents of this directory and how you use it to support your apps, see 「The Library Directory Stores App-Specific Files.」

/Network

This directory contains the list of computers in the local area network.

There is no guarantee that files located on network file servers will have the /Network directory at the beginning of their path. Path names vary depending on several factors, including how the network volume was mounted. For example, if the user uses the Connect to Server command to mount a volume, paths begin with the /Volumes directory. When writing code, assume that files on any volume other than the boot volume could be located on a network-based server.

/System

This directory contains the system resources required by OS X to run. These resources are provided by Apple and must not be modified.

This directory comprises the contents of the system domain.

/Users

This directory contains one or more user home directories. The user home directory is where user-related files are stored. A typical user’s home directory includes the following subdirectories:

  • Applications—Contains user-specific apps.

  • Desktop—Contains the items on the user’s desktop.

  • Documents—Contains user documents and files.

  • Downloads—Contains files downloaded from the Internet.

  • Library—Contains user-specific app files (hidden in OS X 10.7 and later).

  • Movies—Contains the user’s video files.

  • Music—Contains the user’s music files.

  • Pictures—Contains the user’s photos.

  • Public—Contains content the user wants to share.

  • Sites—Contains web pages used by the user’s personal site. (Web Sharing must be enabled to display these pages.)

The preceding directories are for storing user documents and media only. Apps must not write files to the preceding directories unless explicitly directed to do so by the user. The sole exception to this rule is the Library directory, which apps may use to store data files needed to support the current user.

Of the subdirectories, only the Public directory is accessible by other users on the system. Access to the other directories is restricted by default.

Important: The files in the user’s Documents and Desktop directories should reflect only the documents that the user created and works with directly. Similarly, the media directories should contain only the user’s media files. Those directories must never be used to store data files that your app creates and manages automatically. If you need a place to store automatically generated files, use the Library directory, which is designated specifically for that purpose. For information on where to put files in the Library directory, see 「The Library Directory Stores App-Specific Files.」

 

Although the directories in Table 1-2 are the ones seen by OS X users, they are not the only directories present in the file system. OS X hides many directories to prevent users from accessing files that they don’t need to.

Sandboxed OS X App File Containers

OS X apps that are sandboxed have all their Application SupportCache, temporary directories and other related documents stored within a directory located at a system-defined path that you can obtain by calling the NSHomeDirectoryfunction.

For more information see App Sandbox Design Guide.

Hidden Files and Directories: Simplifying the User Experience

To simplify the experience for users, the Finder, and some specific user-facing interfaces (such as the Open and Save panels), hide many files and directories that the user should never have to use. Many of the hidden items are system- or app-specific resources that users cannot (or should not) access directly. Among the files and directories that are hidden are the following:

  • Dot directories and files—Any file or directory whose name starts with a period (.) character is hidden automatically. This convention is taken from UNIX, which used it to hide system scripts and other special types of files and directories. Two special directories in this category are the . and .. directories, which are references to the current and parent directories respectively.

  • UNIX-specific directories—The directories in this category are inherited from traditional UNIX installations. They are an important part of the system’s BSD layer but are more useful to software developers than end users. Some of the more important directories that are hidden include:

    • /bin—Contains essential command-line binaries. Typically, you execute these binaries from command-line scripts.

    • /dev—Contains essential device files, such as mount points for attached hardware.

    • /etc—Contains host-specific configuration files.

    • /sbin—Contains essential system binaries.

    • /tmp—Contains temporary files created by apps and the system.

    • /usr—Contains non-essential command-line binaries, libraries, header files, and other data.

    • /var—Contains log files and other files whose content is variable. (Log files are typically viewed using the Console app.)

  • Explicitly hidden files and directories—The Finder may hide specific files or directories that should not be accessed directly by the user. The most notable example of this is the /Volumes directory, which contains a subdirectory for each mounted disk in the local file system from the command line. (The Finder provides a different user interface for accessing local disks.) In OS X 10.7 and later, the Finder also hides the ~/Library directory—that is, the Librarydirectory located in the user’s home directory.

  • Packages and bundles—Packages and bundles are directories that the Finder presents to the user as if they were files. Bundles hide the internal workings of executables such as apps and just present a single entity that can be moved around the file system easily. Similarly, packages allow apps to implement complex document formats consisting of multiple individual files while still presenting what appears to be a single document to the user.

Although the Finder and other system interfaces hide files and directories from the user, Cocoa interfaces such as NSFileManager do not filter out files or directories that are normally invisible to users. Thus, code that uses these interfaces theoretically has a complete view of the file system and its contents. (Of course, a process really has access to only those files and directories for which it has appropriate permissions.)

Files and Directories Can Have Alternate Names

In some situations, the Finder presents users with file or directory names that do not match the actual names as they appear in the file system. These names are known as display names and are used only by the Finder and specific system components (such as the Open and Save panels) when presenting file and directory information to the user. Display names improve the user experience by presenting the user with content in a more friendly way. For example, OS X uses display names in the following situations:

  • Localized names—The system provides localized names for many system directories, such as ApplicationsLibraryMusicMovies. An app may similarly provide localized names for itself and for any directories it creates.

  • Filename extension hiding—The system hides filename extensions for all files by default. The user may change option, but when filename extension hiding is in effect, the characters after the last period in a filename (and the period itself) are not displayed.

Display names do not affect the actual name of the file in the file system. Code that accesses a file or directory programmatically must specify the item’s actual name when opening or manipulating the item using the file system interfaces. The only time your app should ever use display names is when displaying the name of a file or directory to the user. You can get the display name for any file or directory using the displayNameAtPath: method of NSFileManager.

Important: Your code should not allow users to modify display names directly. When you want the user to specify the name of a file, use a Save panel.

 

For information on how to localize the directories your app creates, see File System Advanced Programming Topics. For more information about localizing app content, see Internationalization Programming Topics.

The Library Directory Stores App-Specific Files

The Library directory is where apps and other code modules store their custom data files. Regardless of whether you are writing code for iOS or OS X, understanding the structure of the Library directory is important. You use this directory to store data files, caches, resources, preferences, and even user data in some specific situations.

There are several Library directories throughout the system but only a few that your code should ever need to access:

  • Library in the current home directory—This is the version of the directory you use the most because it is the one that contains all user-specific files. In iOS, the home directory is the app’s sandbox directory. In OS X, it is the app’s sandbox directory or the current user’s home directory (if the app is not in a sandbox).

  • /Library (OS X only)—Apps that share resources between users store those resources in this version of the Library directory. Sandboxed apps are not permitted to use this directory.

  • /System/Library (OS X only)—This directory is reserved for use by Apple.

After selecting which version of the Library directory to use, you still need to know where to store your files. The Library directory itself contains several subdirectories that subdivide app-specific content into a few well-known categories. Table 1-3lists the most common subdirectories that you might use. Although Library directories in OS X contain many more subdirectories than the ones listed, most are used only by the system. If you want a more complete list of subdirectories, though, see 「OS X Library Directory Details.」

Table 1-3  Key subdirectories of the  Library directory

Directory

Usage

Application Support

Use this directory to store all app data files except those associated with the user’s documents. For example, you might use this directory to store app-created data files, configuration files, templates, or other fixed or modifiable resources that are managed by the app. An app might use this directory to store a modifiable copy of resources contained initially in the app’s bundle. A game might use this directory to store new levels purchased by the user and downloaded from a server.

All content in this directory should be placed in a custom subdirectory whose name is that of your app’s bundle identifier or your company.

In iOS, the contents of this directory are backed up by iTunes.

Caches

Use this directory to write any app-specific support files that your app can re-create easily. Your app is generally responsible for managing the contents of this directory and for adding and deleting files as needed.

In iOS 2.2 and later, the contents of this directory are not backed up by iTunes. In addition, iTunes removes files in this directory during a full restoration of the device.

On iOS 5.0 and later, the system may delete the Cachesdirectory on rare occasions when the system is very low on disk space. This will never occur while an app is running. However, you should be aware that iTunes restore is not necessarily the only condition under which the Caches directory can be erased.

Frameworks

In OS X, frameworks that must be shared by multiple apps can be installed in either the local or user domain. The Frameworks directory in the system domain stores the frameworks you use to create your OS X apps.

In iOS, apps cannot install custom frameworks.

Preferences

This directory contains app-specific preference files. You should not create files in this directory yourself. Instead, use theNSUserDefaults class or CFPreferences API to get and set preference values for your app.

In iOS, the contents of this directory are backed up by iTunes.

The iCloud File Storage Container

3、iCloud 文件存儲容器

iCloud provides a structured system for storing files for apps that make use of iCloud:

iCloud 提供了一個結構系統來存儲應用程序文件,以供iCloud使用:

  • Apps have a primary iCloud container directory for storing their native files.  They can also access secondary iCloud container directories listed in their app entitlements.

    應用程序都有一個主要iCloud容器目錄,用來存儲它們的本地文件。它們還能訪問列在應用程序配置(entitlements)裏的次要iCloud容器目錄。

  • Inside each container directory, files are segregated into "documents" and data.  Every file or file package located in the Documents subdirectory (or one of its subdirectories) is presented to the user (via the iCloud UI in OS X and iOS) as a separate document that can be deleted individually.   Anything not in Documentsor one of its subdirectories is treated as data and shown as a single entry in the iCloud UI.

    在每一個容器目錄裏面,文件被分爲文檔和數據。放置於Documents 子目錄(或是Documents子目錄裏的其中一個)每一個文件或文件包都以一個單獨文檔的方式呈現給用戶,這些文檔能被獨立地刪除。 不在Documents裏或其子目錄裏的任何東西都做爲數據並在iCloud UI 裏以單個視圖顯示。

Documents that the user creates and sees in an app's user interface—for example the document browsers in Pages, Numbers, and Keynote should be stored in theDocuments directory. Another example of files that might go in the Documentsdirectory are saved games, again because they are something that an app could potentially provide some sort of method for selecting.

用戶在一個應用程序的用戶界面裏建立並看到的文檔---好比頁面上的瀏覽的文檔,數字,以及主題(keynote)應該被存儲在Documents目錄。 另外一個可能存儲在Documents 目錄裏的例子是被保存的遊戲,由於它們是應用程序可能提供一些方法以供選擇的一些東西。

Anything that the app does not want the user to see or modify directly should be placed outside of the Documents directory.  Apps can create any subdirectories inside the container directory, so they can arrange private files as desired.

任何應用程序不想用戶看見或直接修改的東西應該被放在Documents 目錄以外。 應用程序能在容器目錄裏建立任何子目錄, 這樣他們就能夠根據須要組織似有文件。

Apps create files and directories in iCloud container directories in exactly the same way as they create local files and directories.  And all the file’s attributes are saved, if they add extended attributes to a file, those attributes are copied to iCloud and to the user's other devices too.

應用程序在iCloud 容器目錄裏建立文件和目錄跟它們建立本地文件和目錄同樣。 並且若是它們給文件添加了擴展屬性,全部的文件屬性都將被保存,同時這些屬性也被拷貝到iCloud 以及用戶的其餘設備中。

iCloud containers also allow the storage of key-value pairs that can be easily accessed without having to create a document format.

iCloud 容器還容許存儲鍵值對,它們能被簡單訪問而不須要建立一個文檔格式。

How the System Identifies the Type of Content in a File

4、系統如何辨別文件裏的內容類型

There are two primary techniques for identifying the type of content in a file:

有兩種主要方法能夠辨別一個文件內容的類型:

  • Uniform Type Identifiers (UTIs)

    統一類型標識符

  • Filename extensions

    文件擴展名

uniform type identifier is a string that uniquely identifies a class of entities considered to have a 「type.」 UTIs provide consistent identifiers for data that all apps and services can recognize and rely upon. They are also more flexible than most other techniques because you can use them to represent any type of data, not just files and directories. Examples of UTIs include:

統一類型標識符是一個字符串,它用來惟一的辨別實體類的類型。UTIs 提供了全部應用程序和服務都能辨認和信賴的一致的數據標識符。 它們也比大多數其它技術更靈活,由於你能夠用它們來表明任何數據類型,不只僅是文件和目錄。 UTIs的例子包括:

  • public.text—A public type that identifies text data.

    一種辨別文本數據的公告類型。

  • public.jpeg—A public type that identifies JPEG image data.

    一種辨別JPEG圖片數據的公共類型。

  • com.apple.bundle—An Apple type that identifies a bundle directory.

    一種辨別一個束目錄的蘋果類型。

  • com.apple.application-bundle—An Apple type that identifies a bundled app.

    一種辨別一個bundled應用程序的蘋果類型。

Whenever a UTI-based interface is available for specifying file types, you should prefer that interface over any others. Many OS X interfaces allow you to specify UTIs corresponding to the files or directories you want to work with. For example, in the Open panel, you can use UTIs as file filters and limit the types of files the user selects to ones your app can handle. Several AppKit classes, including NSDocument,NSPasteboard, and NSImage, support UTIs. In iOS, UTIs are used to specify pasteboard types only.

任什麼時候候當能夠用一個基於UTI的接口來指定文件類型時,你應該優先使用該接口。 不少OS X接口容許你指定跟你想工做的文件或目錄相關的UTIs。好比,在一個打開面板中,你可使用UTIs做爲文件過濾器,並限制用戶選擇應用程序能夠處理的文件類型。一些AppKit類,包括 NSDocument, NSPasteboard, and NSImage 都支持UTIs。在iOS中,UTIs只用於指定粘貼面板類型。

One way the system determines the UTI for a given file is by looking at its filename extension. A filename extension is a string of characters appended to the end of a file and separated from the main filename with a period. Each unique string of characters identifies a file of a specific type. For example, the .strings extension identifies a resource file with localizable string data while the .png extension identifies a file with image data in the portable network graphics format.

系統給一個給定文件決定UTI的一種方法是查看它的文件擴展名。 文件擴展名是追加到文件尾部的一個由字符組成的字符串,它跟主文件名之間以點號分隔。每一個惟一的字符串標識一個特定類型的文件。 好比, .strings擴展名 標識了一個本地化字符串數據的資源文件,而.png擴展名標識一個便攜式網絡圖形格式的圖形數據文件。

Note: Because period characters are valid characters in OS X and iOS filenames, only the characters after the last period in a filename are considered part of the filename extension. Everything to the left of the last period is considered part of the filename itself.

 注意:由於點字符在OS X 和 iOS文件名裏是有效字符,因此只有在文件名裏的最後一個點才被認爲是文件擴展名的一部分。 最後一個點前面的整個部分都是文件名的一部分。

If your app defines custom file formats, you should register those formats and any associated filename extensions in your app’s Info.plist file. TheCFBundleDocumentTypes key specifies the file formats that your app recognizes and is able to open. Entries for any custom file formats should include both a filename extension and UTI corresponding to the file contents. The system uses that information to direct files with the appropriate type to your app.

若是你的應用程序定義了自定義文件格式,你應該在你的應用程序Info.plist文件裏註冊那些格式和相關的文件擴展名。 CFBundleDocumentTypes 鍵指定了應用程序可以辨認並打開的文件格式。任何自定義文件格式應該都包含一個文件擴展名以及跟文件內容相關的UTI。 系統使用這些信息讓文件以適當的類型接入應用程序。

For more information about UTIs and how you use them, see Uniform Type Identifiers Overview. For more information about the CFBundleDocumentTypes key, see Information Property List Key Reference.

關於UTIs的更多信息,以及你如何使用它們,請看 Uniform Type Identifiers Overview. 關於CFBundleDocumentTypes鍵的更多信息,請看Information Property List Key Reference.

Security: Protect the Files You Create

5、安全:保護建立的文件

Because all user data and system code are stored on disk somewhere, protecting the integrity of files and the file system is an important job. For that reason, there are several ways to secure content and prevent it from being stolen or damaged by other processes.

由於全部用戶數據和系統代碼都存儲在磁盤的某個地方,因此保護文件和文件系統的完整性四一項很重要的工做。 由於那個緣由,有不少方法能夠保護內容安全並阻止它被其它進程盜取或損壞。

For general information about secure coding practices when working with files, seeSecure Coding Guide.

關於處理文件時的安全編碼實踐的基本信息,請看Secure Coding Guide.

Sandboxes Limit the Spread of Damage

一、沙盒限制損壞的傳播

In iOS and in OS X v10.7 and later, sandboxes prevent apps from writing to parts of the file system that they should not. Each sandboxed app receives its own container directory in which it can write files. An app cannot write to other apps’ containers or to most directories outside of the sandbox. These restrictions limit the potential damage that can be done in the event that an app’s security is breached.

在iOS 和 OS X v10.7以及以後版本中, 沙盒禁止應用程序向部分它們不該該寫入數據的文件系統寫入數據。每一個沙盒應用程序接收一個本身的容器目錄,在那裏它們能存入各類文件。 應用程序不能寫入其它應用程序的容器內,也不能向沙盒外的大多數目錄你寫入數據。這些限制在應用程序的安全被破壞時能減小事件中的潛在損壞。

Developers writing apps for OS X v10.7 and later are encouraged to put their apps in sandboxes to enhance security. Developers of iOS apps do not have to explicitly put their app in a sandbox because the system does it for them automatically at install time.

推薦編寫OS X v10.7以及以後版本應用程序的開發者把他們的應用程序放入沙盒來加強安全性。iOS應用程序的開發者不須要明確把應用程序放入沙盒,由於系統在下載時自動完成。

For more information about sandboxes and the types of restrictions they impose on file system access, see Mac App Programming Guide and App Sandbox Design Guide.

關於沙盒和它們用於文件系統訪問的限制類型等更多信息,請看Mac App Programming Guide 和 App Sandbox Design Guide.

Permissions and Access Control Lists Govern All Access to Files

二、權限和訪問控制列表管理全部對文件的訪問

Access to files and directories is governed by a mixture of access control lists (ACLs) and BSD permissions. Access control lists are a set of fine-grained controls that define exactly what can and cannot be done to a file or directory and by whom. With access control lists, you can grant individual users different levels of access to a given file or directory. By contrast, BSD permissions only allow you to give access to three classes of users: the file’s owner, a single group of users that you specify, and all users. See Security Overview for more information.

文件和目錄的訪問由訪問控制列表(ACLs)和BSD權限混合控制。訪問控制列表是對文件的一系列詳細控制,它包含什麼能作,什麼不能作,以及誰能作等內容。有了訪問控制列表以後,你就能得到用戶對文件或目錄的不一樣訪問權限。與此相反,BSD權限只容許你給三個用戶類受權:the file's owner(文件全部者),你指定的單個用戶組,以及全部用戶。請看Security Overview 瞭解更多詳情。

Note: For a file on a network server, do not make any assumptions about the ACLs and BSD permissions associated with the file. Some network file systems provide only a summarized version of this information.

 注意:對於一個網絡服務器上的文件,不作任何與該文件相關的ACL的和BSD權限的假設。一些網絡文件系統只能提供這些信息的總結版本。

Because iOS apps always run in a sandbox, the system assigns specific ACLs and permissions to files created by each app. However, OS X apps can use Identity Services to manage access control lists for files to which they have access. For information about how to use Identity Services (and the Collaboration framework), see Identity Services Programming Guide.

由於iOS應用程序永遠只在一個沙盒裏運行, 系統給每一個應用程序的文件分配了特定的ACL和權限。然而,OS X 應用程序能夠給它們已經訪問的文件使用身份服務來管理訪問控制列表。關於如何使用身份服務(以及Collaboration 框架)的信息,請看Identity Services Programming Guide.

Files Can Be Encrypted On Disk

三、 磁盤上的文件可加密

Both OS X and iOS provide support for encrypting files on disk:

OS X 和 iOS均可以對磁盤的文件加密:

  • iOS—An iOS app can designate files that it wants to be encrypted on disk. When the user unlocks a device containing encrypted files, the system creates a decryption key that allows the app to access its encrypted files. When the user locks the device, though, the decryption key is destroyed to prevent unauthorized access to the files.

    iOS--iOS應用程序能夠指定磁盤中它想加密的文件。 當用戶解鎖包含加密文件的設備時,系統建立一個解密祕鑰讓應用程序訪問它的加密文件。當用戶鎖設備時,該解密祕鑰就被摧毀以阻止對該文件的非法訪問。

  • OS X—Users can encrypt the contents of a volume using the Disk Utility app. (They can also encrypt just the boot volume from the Security & Privacy system preference.) The contents of an encrypted disk are available to apps only while the computer is running. When the user puts the computer to sleep or shuts it down, the decryption keys are destroyed to prevent unauthorized access to the disk’s contents.

    OS X--用戶可使用磁盤實用應用程序對卷內容進行加密。(它們也能夠在Security & Privacy system preference只給啓動捲進行加密。) 應用程序只能在電腦運行時才恩那個使用一個加密磁盤的內容。當用戶讓電腦進入睡眠或關閉時,解密祕鑰就被摧毀以阻止非法訪問磁盤的內容。

In iOS, apps that take advantage of disk-based encryption need to be discontinue the use of encrypted files when the user locks the device. Because locking the device destroys the decryption keys, access to encrypted files is limited to when the device is unlocked. If your iOS app can run in the background while the device is locked, it must do so without access to any of its encrypted files. Because encrypted disks in OS X are always accessible while the computer is running, OS X apps do not need to do anything special to handle disk-level encryption.

在iOS中,當用戶鎖定設備時,使用基於磁盤加密的應用程序須要中止使用文件加密。 由於鎖定設備摧毀解密祕鑰, 訪問加密文件只限於當設備不被鎖定時。當設備被鎖定時,若是你的iOS應用程序能在後臺運行,它必須不能訪問任何它的加密文件。由於在OS X中的加密磁盤在電腦運行時老是可訪問, OS X 應用程序不須要作任何特殊事情來處理磁盤層的加密。

For more information about working with encrypted files in iOS, see iOS App Programming Guide.

關於iOS中有關加密文件的更多信息,請看 iOS App Programming Guide.

Synchronization Ensures Robustness in Your File-Related Code

6、同步可確保你的文件相關代碼的健壯性

The file system is a resource shared by third-party apps and system apps. Because multiple apps are able to access files and directories at the same time, the potential arises for one app to make changes that render a second app’s view of the file system obsolete. If the second app is not prepared to handle such changes, it could enter an unknown state or even crash. In cases where your app relies on the presence of specific files, you can use synchronization interfaces to be notified of changes to those files.

文件系統是被第三方應用程序和系統應用程序共享的一個資源。由於多個應用程序能夠同時訪問文件和目錄, 因此就有可能出現一個應用程序的修改致使第二個應用程序的文件系統視圖過期的現象。若是第二個應用程序沒有準備處理這樣的改變,它可能進入一個未知的狀態甚至奔潰。在你的應用程序依賴指定文件是否存在的狀況下,你可使用同步接口來接收對那些文件的改變。

File system synchronization is primarily an issue in OS X, where the user can manipulate files directly with the Finder or with any number of other apps at the same time. Fortunately, OS X provides the following interfaces to help with synchronization issues:

文件系統同步主要是OS X裏的一個問題,在OS X裏用戶能夠經過Finder或不少其它應用程序同時直接操做文件。 幸運的是,OS X提供瞭如下接口來幫助同步問題:

Files, Concurrency, and Thread Safety

7、文件,併發,以及線程安全

Because file-related operations involve interacting with the hard disk and are therefore slow compared to most other operations, most of the file-related interfaces in iOS and OS X are designed with concurrency in mind. Several technologies incorporate asynchronous operation into their design and most others can execute safely from a dispatch queue or secondary thread. Table 1-4 lists some of the key technologies discussed in this document and whether they are safe to use from specific threads or any thread. For specific information about the capabilities of any interface, see the reference documentation for that interface.

由於文件相關的操做涉及與硬件磁盤的交互,因此相比於其它操做比較慢,大多數文件相關的接口在iOS 和 OS X中都設計帶有併發。表1-4 列出了一些在本文檔中討論的關鍵技術,以及它們從特定線程或任何線程中使用是否安全。 對於有關任何接口的能力的特定信息,請看那個接口的參考文檔。

Table 1-4  Thread safety of key classes and technologies表 1-4 關鍵類和技術的線程安全

Class/Technology

Notes

NSFileManager

For most tasks, it is safe to use the default NSFileManagerobject simultaneously from multiple background threads. The only exception to this rule is tasks that interact with the file manager’s delegate. When using a file manager object with a delegate, it is recommended that you create a unique instance of the NSFileManager class and use your delegate with that instance. You should then use your unique instance from one thread at a time.

對於大多數任務,從多個後臺線程同時使用默認的NSFileManager 對象是安全的。惟一例外是當任務跟文件管理者的委託(file manager's delegate)發生交互時。當一個委託使用一個文件管理者對象時,推薦你建立一個惟一的NSFileManager實例,並讓你的委託跟該實例一塊兒使用。而後你應該在一個時間從一個線程使用你的惟一實例。

Grand Central Dispatch

GCD itself is safe to use from any thread. However, you are still responsible for writing your blocks in a way that is thread safe.

GCD自己在任何線程使用都是安全的。可是,你任然有責任考慮線程安全編寫你的塊。

NSFileHandle,NSData, Cocoa streams

Most of the Foundation objects you use to read and write file data can be used from any single thread but should not be used from multiple threads simultaneously.

大多數你用來讀取和寫入文件數據的基礎對象都能在任何單個線程中使用,可是不該該同時在多個線程使用。

Open and Save panels

Because they are part of your user interface, you should always present and manipulate the Open and Save panels from your app’s main thread.

由於它們是你的用戶界面的一部分,你應該老是從你的應用程序主線程中呈現並操做Open and Save 面板。

POSIX routines

The POSIX routines for manipulating files are generally designed to operate safely from any thread. For details, see the corresponding man pages.

POSIX 例程 用來操做文件通常都是從任何線程操做都是安全的。詳情請看相關手冊頁。

NSURL andNSString

The immutable objects you use to specify paths are safe to use from any thread. Because they are immutable, you can also refer to them from multiple threads simultaneously. Of course, the mutable versions of these objects should be used from only one thread at a time.

你用來指定路徑的固定不變的對象在任何線程使用都是安全的。 由於它們是一成不變的,你還能夠同時在多個線程引用它們。 固然,這些對象的可變版本只能一個時間在一個線程中使用。

NSEnumeratorand its subclasses

Enumerator objects are safe to use from any single thread but should not be used from multiple threads simultaneously.

枚舉對象在任何單個線程中使用都是安全的,可是不該該同時在多個線程使用。

Even if you use an thread-safe interface for manipulating a file, problems can still arise when multiple threads or multiple processes attempt to act on the same file. Although there are safeguards to prevent multiple clients from modifying a file at the same time, those safeguards do not always guarantee exclusive access to the file at all times. (Nor should you attempt to prevent other processes from accessing shared files.) To make sure your code knows about changes made to shared files, use file coordinators to manage access to those files. For more information about file coordinators, see 「The Role of File Coordinators and Presenters」

即便你使用一個線程安全接口來操做一個文件,當對個線程或多個進程嘗試操做同一個文件時,問題仍是會發生。雖然有保障措施,以防止多個客戶端同時修改文件,可是這些措施不會老是保證任什麼時候候都能獨佔訪問該文件。(你也不該該嘗試阻止其它進程訪問共享文件。)要想確保你的代碼瞭解對共享文件所在的改變,使用文件協調員(file coordinators)來管理那些文件的訪問。 關於文件協調員的更多信息,請看 「The Role of File Coordinators and Presenters」

相關文章
相關標籤/搜索