A file system handles 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.
- A 文件系統處理數據文件,應用程序以及與操作系統本身相關的文件的持久存儲。 因此,文件系統是所有進程使用的基本資源之一。
APFS is the default file system in macOS, iOS, watchOS, and tvOS. APFS replaces HFS+ as the default file system for iOS 10.3 and later, and macOS High Sierra and later. macOS additionally supports a variety of other formats, as described in Supported File Systems.
- APFS是macOS,iOS,watchOS和tvOS中的默認文件系統。 APFS將HFS +替換為iOS 10.3及更高版本以及macOS High Sierra及更高版本的默認文件系統。 macOS還支持各種其他格式,如支持的文件系統中所述。
Regardless of the underlying format, all of the disks attached to the device—whether they are physically plugged in 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 macOS, there are differences in the way each system organizes apps and user data.
- 無論基礎格式如何,連接到設備的所有磁盤 - 無論是物理插入還是通過網絡間接連接 - 都會創建單個文件集合。 由于文件數量很容易達到數百萬,
因此文件系統使用目錄來創建分層組織
。 雖然iOS和macOS的基本目錄結構相似,但每個系統組織應用程序和用戶數據的方式各不相同。
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
- 關于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設備的用戶無法直接訪問文件系統,并且應用程序應遵循此約定。
iOS Standard Directories: Where Files Reside
- iOS標準目錄:文件駐留的位置
For security purposes, an iOS app’s interactions with the file system are limited to the directories inside the app’s sandbox directory. During installation of a new app, the installer creates a number of container directories for the app inside the sandbox directory. Each container directory has a specific role. The bundle container directory holds the app’s bundle, whereas the data container directory holds data for both the app and the user. The data container directory is further divided into a number of subdirectories that the app can use to sort and organize its data. The app may also request access to additional container directories—for example, the iCloud container—at runtime. - 出于安全考慮,iOS應用程序與文件系統的交互僅限于應用程序沙盒中的目錄。 在安裝新應用程序期間,安裝程序會在沙盒目錄中為應用程序創建許多容器目錄。 每個容器目錄都有一個特定的角色。 包容器目錄包含應用程序包,而數據容器目錄包含應用程序和用戶的數據。 數據容器目錄進一步劃分為許多子目錄,應用程序可以使用這些子目錄對數據進行排序和組織。 應用程序還可以在運行時請求訪問其他容器目錄(例如,iCloud容器)。
These container directories constitute the app’s primary view of the file system. Figure 1-1 shows a representation of the sandbox directory for an app.
- 這些容器目錄構成了應用程序的文件系統主視圖。 圖1-1顯示了應用程序的沙箱目錄的表示。
在自己的沙箱目錄中運行的iOS應用程序
An app is generally prohibited from accessing or creating files outside its container directories. One exception to this rule is when an app uses public system interfaces to access things such as the user’s contacts or music. In those cases, the system frameworks use helper apps to handle any file-related operations needed to read from or modify the appropriate data stores.
- 通常禁止應用程序訪問或創建容器目錄之外的文件。 此規則的一個例外是當應用程序使用公共系統接口訪問用戶的聯系人或音樂等內容時。 在這些情況下,系統框架使用幫助應用程序來處理讀取或修改適當數據存儲所需的任何與文件相關的操作。
Table 1-1 lists some of the more important subdirectories inside the sandbox 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 and iCloud.
- 表1-1列出了sandbox目錄中一些更重要的子目錄,并描述了它們的預期用法。 此表還描述了每個子目錄的任何其他訪問限制,并指出目錄的內容是否由iTunes和iCloud備份。
Table 1-1 Commonly used directories of an iOS app
- 常用的iOS應用程序目錄
Directory1 :AppName.app
Description: This is the app’s bundle. This directory contains the app and all of its resources.
- 這是應用程序的捆綁包。 該目錄包含應用程序及其所有資源。
You cannot write 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. You can, however, gain read-only access to any resources stored in the apps bundle. For more information, see the Resource Programming Guide
- 您無法寫入此目錄。 為防止篡改,bundle目錄在安裝時簽名。 寫入此目錄會更改簽名并阻止您的應用啟動。 但是,您可以獲得對應用程序包中存儲的任何資源的只讀訪問權限。 有關更多信息,請參閱“資源編程指南”
The contents of this directory are not backed up by iTunes or iCloud. However, iTunes does perform an initial sync of any apps purchased from the App Store.
- iTunes或iCloud不會備份此目錄的內容。 但是,iTunes確實執行從App Store購買的任何應用程序的初始同步。
Directory2 : Documents/
Description: Use this directory to store user-generated content. The contents of this directory can be made available to the user through file sharing; therefore, his directory should only contain files that you may wish to expose to the user.
The contents of this directory are backed up by iTunes and iCloud.
- 使用此目錄存儲用戶生成的內容。 該目錄的內容可以通過文件共享提供給用戶; 因此,他的目錄應該只包含您可能希望向用戶公開的文件。
該目錄的內容由iTunes和iCloud備份。
Directory3 : Documents/Inbox
Description: 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.
- 使用此目錄可以訪問外部實體要求您打開應用程序的文件。 具體來說,Mail程序將與您的應用程序關聯的電子郵件附件放在此目錄中。 文檔交互控制器也可以在其中放置文件。
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 and iCloud.
- 您的應用可以讀取和刪除此目錄中的文件,但無法創建新文件或寫入現有文件。 如果用戶嘗試編輯此目錄中的文件,則在進行任何更改之前,您的應用必須以靜默方式將其移出目錄。
該目錄的內容由iTunes和iCloud備份。
Directory4 : Library/
Description: This is the top-level directory for any files that are not user data files. You typically put files in one of several standard subdirectories. iOS apps commonly use the Application Support
and Caches
subdirectories; however, you can create custom subdirectories.
- 這是非用戶數據文件的任何文件的頂級目錄。 您通常將文件放在幾個標準子目錄之一中。 iOS應用程序通常使用Application Support和Caches子目錄; 但是,您可以創建自定義子目錄。
Use the Library
subdirectories for any files you don’t want exposed to the user. Your app should not use these directories for user data files.
- 對于您不希望向用戶公開的任何文件,請使用Library子目錄。 您的應用不應將這些目錄用于用戶數據文件。
The contents of the Library
directory (with the exception of the Caches
subdirectory) are backed up by iTunes and iCloud.
- “Library”目錄的內容(“Caches”子目錄除外)由iTunes和iCloud備份。
For additional information about the Library directory and its commonly used subdirectories, see The Library Directory Stores App-Specific Files.
- 有關Library目錄及其常用子目錄的其他信息,請參閱庫目錄存儲特定于應用程序的文件。
Directory5 : tmp/
Description:
Description: 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 they are no longer needed; however, the system may purge this directory when your app is not running.
- 使用此目錄可以編寫在應用程序啟動之間不需要保留的臨時文件。 您的應用程序應在不再需要時刪除此目錄中的文件; 但是,當您的應用未運行時,系統可能會清除此目錄。
The contents of this directory are not backed up by iTunes or iCloud.
- iTunes或iCloud不會備份此目錄的內容。
An iOS app may create additional directories in the Documents
, Library
, and tmp
directories. You might do this to better organize the files in those locations.
- 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應用程序獲取對前面目錄的引用的信息,請參閱在標準目錄中查找項目。 有關放置文件的位置的提示,請參閱應放置應用程序文件的位置。
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. 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
Documents/
. User data generally includes any files you might want to expose to the user—anything you might want the user to create, import, delete or edit. For a drawing app, user data includes any graphic files the user might create. For a text editor, it includes the text files. Video and audio apps may even include files that the user has downloaded to watch or listen to later.- 將用戶數據放在Documents /中。 用戶數據通常包括您可能希望向用戶公開的任何文件 - 您可能希望用戶創建,導入,刪除或編輯的任何文件。 對于繪圖應用程序,用戶數據包括用戶可能創建的任何圖形文件。 對于文本編輯器,它包含文本文件。 視頻和音頻應用程序甚至可能包含用戶下載后觀看或收聽的文件。
-
Put app-created support files in the
Library/Application support/
directory. In general, this directory includes files that the app uses to run but that should remain hidden from the user. This directory can also include data files, configuration files, templates and modified versions of resources loaded from the app bundle.- 將應用程序創建的支持文件放在庫/應用程序支持/目錄中。 通常,此目錄包含應用程序用于運行但應保持對用戶隱藏的文件。 此目錄還可以包括從應用程序包加載的數據文件,配置文件,模板和已修改的資源版本。
-
Remember that files in
Documents/
andApplication Support/
are backed up by default. You can exclude files from the backup by calling-[NSURL setResourceValue:forKey:error:]
using theNSURLIsExcludedFromBackupKey
key. Any file that can be re-created or downloaded must be excluded from the backup. This is particularly important for large media files. If your application downloads video or audio files, make sure they are not included in the backup.- 請記住,默認情況下會備份Documents /和Application Support /中的文件。 您可以使用NSURLIsExcludedFromBackupKey鍵調用[NSURL setResourceValue:forKey:error:]從備份中排除文件。 必須從備份中排除任何可以重新創建或下載的文件。 這對于大型媒體文件尤為重要。 如果您的應用程序下載視頻或音頻文件,請確保它們不包含在備份中。
-
Put temporary data in the
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. The system will periodically purge these files when your app is not running; therefore, you cannot rely on these files persisting after your app terminates.- 將臨時數據放在tmp /目錄中。 臨時數據包括您不需要長時間保留的任何數據。 請記住在完成這些文件后刪除這些文件,以便它們不會繼續消耗用戶設備上的空間。 當您的應用未運行時,系統會定期清除這些文件; 因此,您的應用程序終止后,您不能依賴這些文件。
-
Put data cache files in the
Library/Caches/
directory. Cache data can be used for any data that needs to persist longer than temporary data, but not as long as a support file. Generally speaking, the application does not require cache data to operate properly, but it can use cache data to improve performance. Examples of cache data include (but are not limited to) database cache files and transient, downloadable content. Note that the system may delete theCaches/
directory to free up disk space, so your app must be able to re-create or download these files as needed.- 將數據緩存文件放在Library / Caches /目錄中。 緩存數據可用于需要比臨時數據持續更長時間的任何數據,但不能與支持文件一樣長。 一般來說,應用程序不需要緩存數據正常運行,但它可以使用緩存數據來提高性能。 高速緩存數據的示例包括(但不限于)數據庫高速緩存文件和瞬態可下載內容。 請注意,系統可能會刪除Caches /目錄以釋放磁盤空間,因此您的應用必須能夠根據需要重新創建或下載這些文件。
How the System Identifies the Type of Content in a File
- 系統如何識別文件中的內容類型
There are two primary techniques for identifying the type of content in a file:
- 有兩種主要技術可用于識別文件中的內容類型:
Uniform Type Identifiers (UTIs): 統一類型標識符(UTI)
Filename extensions: 文件擴展名
A 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:
- 統一類型標識符是唯一標識被認為具有“類型”的實體類的字符串.UTI為所有應用和服務可識別和依賴的數據提供一致的標識符。 它們也比大多數其他技術更靈活,因為您可以使用它們來表示任何類型的數據,而不僅僅是文件和目錄。 UTI的例子包括:
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.
- 標識捆綁目錄的Apple類型。
com.apple.application-bundle—An Apple type that identifies a bundled app.
- 標識捆綁應用的Apple類型。
Whenever a UTI-based interface is available for specifying file types, you should prefer that interface over any others. Many macOS 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的接口可用于指定文件類型時,您應該優先于任何其他接口。 許多macOS接口允許您指定與要使用的文件或目錄相對應的UTI。 例如,在“打開”面板中,您可以將UTI用作文件篩選器,并將用戶選擇的文件類型限制為應用程序可以處理的文件類型。 幾個AppKit類,包括NSDocument,NSPasteboard和NSImage,都支持UTI。 在iOS中,UTI僅用于指定粘貼板類型。
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 macOS 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.
- 由于句點字符是macOS和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. The CFBundleDocumentTypes
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.
Files Can Be Encrypted On Disk
Both macOS and iOS provide support for encrypting files on disk:
-
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應用程序可以指定要在磁盤上加密的文件。 當用戶解鎖包含加密文件的設備時,系統會創建一個解密密鑰,允許該應用訪問其加密文件。 但是,當用戶鎖定設備時,破解解密密鑰以防止對文件的未授權訪問。
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 macOS are always accessible while the computer is running, macOS apps do not need to do anything special to handle disk-level encryption.
- 在iOS中,利用基于磁盤的加密的應用程序需要在用戶鎖定設備時停止使用加密文件。 由于鎖定設備會破壞解密密鑰,因此對加密文件的訪問僅限于設備解鎖時。 如果您的iOS應用程序可以在設備鎖定時在后臺運行,則必須在不訪問任何加密文件的情況下執行此操作。 由于macOS中的加密磁盤在計算機運行時始終可以訪問,因此macOS應用程序無需執行任何特殊操作即可處理磁盤級加密。
For more information about working with encrypted files in iOS, see App Programming Guide for iOS.
Files, Concurrency, and Thread Safety
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 macOS 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和macOS中的大多數與文件相關的接口都考慮了并發性。 有幾種技術將異步操作合并到其設計中,而大多數其他技術可以從調度隊列或輔助線程安全地執行。 表1-4列出了本文檔中討論的一些關鍵技術,以及它們是否可以安全地從特定線程或任何線程使用。 有關任何接口功能的特定信息,請參閱該接口的參考文檔。
-
NSFileManager
For most tasks, it is safe to use the default NSFileManager object 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對象。 此規則的唯一例外是與文件管理器委托交互的任務。 將文件管理器對象與委托一起使用時,建議您創建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.
- 您用于讀取和寫入文件數據的大多數Foundation對象都可以在任何單個線程中使用,但不應同時從多個線程使用。
- 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.
- 因為它們是用戶界面的一部分,所以應始終在應用程序的主線程中顯示和操作“打開”和“保存”面板。
- 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
and
NSString
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.
- 用于指定路徑的不可變對象可以安全地從任何線程使用。 因為它們是不可變的,所以您也可以同時從多個線程中引用它們。 當然,這些對象的可變版本一次只能在一個線程中使用。
-
NSEnumerator and 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
- 即使您使用線程安全接口來操作文件,當多個線程或多個進程嘗試對同一文件執行操作時,仍會出現問題。 盡管存在防止多個客戶端同時修改文件的安全措施,但這些安全措施并不總能保證對文件的獨占訪問。 (您也不應該嘗試阻止其他進程訪問共享文件。)要確保您的代碼知道對共享文件所做的更改,請使用文件協調器來管理對這些文件的訪問。 有關文件協調器的更多信息,請參閱文件協調器和演示者的角色