Accessing Files and Directories(-)

相關(guān)鏈接:
https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW1

Before you can open a file, you first have to locate it in the file system. The system frameworks provide many routines for obtaining references to many well-known directories, such as the Library directory and its contents. You can also specify locations manually by building a URL or string-based path from known directory names.

  • 在打開(kāi)文件之前,首先必須在文件系統(tǒng)中找到它。 系統(tǒng)框架提供了許多例程來(lái)獲取對(duì)許多知名目錄的引用,例如Library目錄及其內(nèi)容。 您還可以通過(guò)從已知目錄名構(gòu)建URL或基于字符串的路徑來(lái)手動(dòng)指定位置。

When you know the location of a file, you can then start planning the best way to access it. Depending on the type of file, you may have several options. For known file types, you typically use built-in system routines to read or write the file contents and give you an object that you can use. For custom file types, you may need to read the raw file data yourself.

  • 當(dāng)您知道文件的位置時(shí),您就可以開(kāi)始規(guī)劃訪問(wèn)它的最佳方式。 根據(jù)文件類型,您可能有多個(gè)選項(xiàng)。 對(duì)于已知的文件類型,通常使用內(nèi)置系統(tǒng)例程來(lái)讀取或?qū)懭胛募?nèi)容,并為您提供可以使用的對(duì)象。 對(duì)于自定義文件類型,您可能需要自己讀取原始文件數(shù)據(jù)。

Choose the Right Way to Access Files

  • 選擇正確的方式來(lái)訪問(wèn)文件
    Although you can open any file and read its contents as a stream of bytes, doing so is not always the right choice. macOS and iOS provide built-in support that makes opening many types of standard file formats (such as text files, images, sounds, and property lists) much easier. For these standard file formats, use the higher-level options for reading and writing the file contents. Table 2-1 lists the common file types supported by the system along with information about how you access them.
  • 雖然您可以打開(kāi)任何文件并將其內(nèi)容作為字節(jié)流讀取,但這樣做并不總是正確的選擇。 macOS和iOS提供內(nèi)置支持,可以更輕松地打開(kāi)多種類型的標(biāo)準(zhǔn)文件格式(如文本文件,圖像,聲音和屬性列表)。 對(duì)于這些標(biāo)準(zhǔn)文件格式,請(qǐng)使用更高級(jí)別的選項(xiàng)來(lái)讀取和寫(xiě)入文件內(nèi)容。 表2-1列出了系統(tǒng)支持的常用文件類型以及有關(guān)如何訪問(wèn)它們的信息。

Table 2-1 File types with specialized routines

  • 具有專門(mén)例程的文件類型
  1. File Type: Resource files
    Examples : Nib files,* Image files*, Sound files, Strings files, Localized resources
    Description: Apps use resource files to store data that is independent of the code that uses it. Resource files are commonly used to store localizable content such as strings and images. The process for reading data from a resource file depends on the resource type.
  • 應(yīng)用程序使用資源文件來(lái)存儲(chǔ)獨(dú)立于使用它的代碼的數(shù)據(jù)。 資源文件通常用于存儲(chǔ)可本地化的內(nèi)容,例如字符串和圖像。 從資源文件讀取數(shù)據(jù)的過(guò)程取決于資源類型。

For information about how to read the contents of resource files, see Resource Programming Guide.

  • 有關(guān)如何讀取資源文件內(nèi)容的信息,請(qǐng)參閱“資源編程指南”。
  1. File Type: Text files
    Examples : Plain text file,UTF-8 formatted file,UTF-16 formatted file
    Description: A text file is an unstructured sequence of ASCII or Unicode characters. You typically load the contents of a text file into an NSString object but may also read and write a text file as a raw stream of characters.
  • 文本文件是ASCII或Unicode字符的非結(jié)構(gòu)化序列。 您通常將文本文件的內(nèi)容加載到NSString對(duì)象中,但也可以讀取和寫(xiě)入文本文件作為原始字符流。

For information about using the NSString class to load text from a file, see String Programming Guide.

  • 有關(guān)使用NSString類從文件加載文本的信息,請(qǐng)參閱“字符串編程指南”。
  1. File Type: Structured data files
    Examples : XML file,Property list file,Preference file
    Description: A structured data file usually consists of string-based data arranged using a set of special characters.
  • 結(jié)構(gòu)化數(shù)據(jù)文件通常由使用一組特殊字符排列的基于字符串的數(shù)據(jù)組成。

For information about parsing XML, see Event-Driven XML Programming Guide.

  • 有關(guān)解析XML的信息,請(qǐng)參閱“事件驅(qū)動(dòng)的XML編程指南”。
  1. File Type: Archive files
    Examples : Binary files created using a keyed archiver object
    Description: An archive is a file format used to store a persistent version of your app’s runtime objects. An archiver object encodes the state of the objects into a stream of bytes that can be written to disk all at once. An unarchiver reverses the process, using the stream of bytes to re-create the objects and restore them to their previous state.
  • 存檔是一種文件格式,用于存儲(chǔ)應(yīng)用程序運(yùn)行時(shí)對(duì)象的持久版本。 歸檔程序?qū)ο髮?duì)象的狀態(tài)編碼為可以一次寫(xiě)入磁盤(pán)的字節(jié)流。 unarchiver反轉(zhuǎn)進(jìn)程,使用字節(jié)流重新創(chuàng)建對(duì)象并將其恢復(fù)到以前的狀態(tài)。

Archives are often a convenient alternative to implementing custom binary file formats for your documents or other data files.

  • 歸檔通常是為文檔或其他數(shù)據(jù)文件實(shí)現(xiàn)自定義二進(jìn)制文件格式的便捷替代方法。

For information on how to create and read archive files, see Archives and Serializations Programming Guide.

  • 有關(guān)如何創(chuàng)建和讀取存檔文件的信息,請(qǐng)參閱存檔和序列化編程指南。
  1. File Type: File packages
    Examples : Custom document formats
    Description: A file package is a directory that contains any number of custom data files but which is presented to the user as if it were a single file. Apps can use file packages to implement complex file formats that contain multiple distinct files, or a mixture of different types of files. For example, you might use a file package if your file format includes both a binary data file and one or more image, video, or audio files. You access the contents of a file package using NSFileWrapper objects, as described in Using FileWrappers as File Containers.
  • 文件包是一個(gè)目錄,它包含任意數(shù)量的自定義數(shù)據(jù)文件,但它們就像是單個(gè)文件一樣呈現(xiàn)給用戶。 應(yīng)用程序可以使用文件包來(lái)實(shí)現(xiàn)包含多個(gè)不同文件的復(fù)雜文件格式,或者混合使用不同類型的文件。 例如,如果文件格式包含二進(jìn)制數(shù)據(jù)文件和一個(gè)或多個(gè)圖像,視頻或音頻文件,則可以使用文件包。 您可以使用NSFileWrapper對(duì)象訪問(wèn)文件包的內(nèi)容,如使用FileWrappers作為文件容器中所述。
  1. File Type: Bundles
    Examples : Apps,Plug-ins, Frameworks
    Description: Bundles provide a structured environment for storing code and the resources used by that code. Most of the time, you do not work with the bundle itself but with its contents. However, you can locate bundles and obtain information about them as needed.
  • Bundles提供了一個(gè)結(jié)構(gòu)化的環(huán)境,用于存儲(chǔ)代碼和該代碼使用的資源。 大多數(shù)情況下,您不使用包本身,而是使用其內(nèi)容。 但是,您可以根據(jù)需要找到捆綁包并獲取有關(guān)它們的信息。

For information about bundles and how you access them, see Bundle Programming Guide

  • 有關(guān)捆綁包以及如何訪問(wèn)它們的信息,請(qǐng)參閱捆綁包編程指南
  1. File Type: Code files
    Examples : Binary code resources, Dynamic shared libraries
    Description: Apps that work with plug-ins and shared libraries need to be able to load the associated code for that item to take advantage of its functionality.
  • 使用插件和共享庫(kù)的應(yīng)用程序需要能夠加載該項(xiàng)目的關(guān)聯(lián)代碼以利用其功能。

For information about how to load code resources into memory, see Code Loading Programming Topics.

  • 有關(guān)如何將代碼資源加載到內(nèi)存的信息,請(qǐng)參閱代碼加載編程主題。

In situations where the standard file formats are insufficient, you can always create your own custom file formats. When reading and writing the content of custom files, you read and write data as a stream of bytes and apply those bytes to your app’s file-related data structures. You have complete control over how you read and write the bytes and how you manage your file-related data structures. For more information about the techniques for reading and writing files that use custom file formats, see Techniques for Reading and Writing Files Without File Coordinators.

  • 在標(biāo)準(zhǔn)文件格式并不是很高效的情況下,您可以創(chuàng)建自己的自定義文件格式。 在讀取和寫(xiě)入自定義文件的內(nèi)容時(shí),您可以將數(shù)據(jù)作為字節(jié)流讀取和寫(xiě)入,并將這些字節(jié)應(yīng)用于應(yīng)用程序的文件相關(guān)數(shù)據(jù)結(jié)構(gòu)。 您可以完全控制如何讀取和寫(xiě)入字節(jié)以及如何管理與文件相關(guān)的數(shù)據(jù)結(jié)構(gòu)。 有關(guān)讀取和寫(xiě)入使用自定義文件格式的文件的技術(shù)的詳細(xì)信息,請(qǐng)參閱無(wú)文件協(xié)調(diào)器的讀取和寫(xiě)入文件的技術(shù)。

Specifying the Path to a File or Directory

  • 指定文件或目錄的路徑

The preferred way to specify the location of a file or directory is to use the [NSURL](https://developer.apple.com/documentation/foundation/nsurl) class. Although the [NSString](https://developer.apple.com/library/archive/documentation/LegacyTechnologies/WebObjects/WebObjects_3.5/Reference/Frameworks/ObjC/Foundation/Classes/NSStringClassCluster/Description.html#//apple_ref/occ/cl/NSString) class has many methods related to path creation, URLs offer a more robust way to locate files and directories. For apps that also work with network resources, URLs also mean that you can use one type of object to manage items located on a local file system or on a network server.

  • 指定文件或目錄位置的首選方法是使用NSURL類。 雖然NSString類有許多與路徑創(chuàng)建相關(guān)的方法,但URL提供了一種更健壯的方法來(lái)定位文件和目錄。 對(duì)于也使用網(wǎng)絡(luò)資源的應(yīng)用程序,URL還意味著您可以使用一種類型的對(duì)象來(lái)管理位于本地文件系統(tǒng)或網(wǎng)絡(luò)服務(wù)器上的項(xiàng)目。

Note: In addition to NSURL, you can also use the CFURLRef opaque type to manipulate paths as URLs. The NSURL class is toll-free bridged with the CFURLReftype, which means you can use them interchangeably in your code. For more information about how to create and manipulate URLs using Core Foundation, see CFURL Reference.

  • 注意:除了NSURL之外,您還可以使用CFURLRef opaque類型將路徑作為URL進(jìn)行操作。 NSURL類與CFURLReftype進(jìn)行免費(fèi)橋接,這意味著您可以在代碼中交替使用它們。 有關(guān)如何使用Core Foundation創(chuàng)建和操作URL的更多信息,請(qǐng)參閱CFURL參考。

For most URLs, you build the URL by concatenating directory and file names together using the appropriate NSURL methods until you have the path to the item. A URL built in that way is referred to as a path-based URL because it stores the names needed to traverse the directory hierarchy to locate the item. (You also build string-based paths by concatenating directory and file-names together, with the results stored in a slightly different format than that used by the NSURL class.) In addition to path-based URLs, you can also create a file reference URL, which identifies the location of the file or directory using a unique ID.

  • 對(duì)于大多數(shù)URL,您可以通過(guò)使用適當(dāng)?shù)腘SURL方法將目錄和文件名連接在一起來(lái)構(gòu)建URL,直到獲得該項(xiàng)的路徑。 以這種方式構(gòu)建的URL稱為基于路徑的URL,因?yàn)樗鎯?chǔ)遍歷目錄層次結(jié)構(gòu)以查找項(xiàng)目所需的名稱。 (您還可以通過(guò)將目錄和文件名連接在一起來(lái)構(gòu)建基于字符串的路徑,結(jié)果的格式與NSURL類使用的格式略有不同。)除了基于路徑的URL,您還可以創(chuàng)建文件引用 URL,使用唯一ID標(biāo)識(shí)文件或目錄的位置。

All of the following entries are valid references to a file called MyFile.txt in a user’s Documents directory:

  • 以下所有條目都是對(duì)用戶的Documents目錄中名為MyFile.txt的文件的有效引用:

Path-based URL: file://localhost/Users/steve/Documents/MyFile.txt

File reference URL: file:///.file/id=6571367.2773272/

String-based path: /Users/steve/Documents/MyFile.txt

You create URL objects using the NSURL methods and convert them to file reference URLs only when needed. Path-based URLs are easier to manipulate, easier to debug, and are generally preferred by classes such as NSFileManager. An advantage of file reference URLs is that they are less fragile than path-based URLs while your app is running. If the user moves a file in the Finder, any path-based URLs that refer to the file immediately become invalid and must be updated to the new path. However, as long as the file moved to another location on the same disk, its unique ID does not change and any file reference URLs remain valid.

  • 您可以使用NSURL方法創(chuàng)建URL對(duì)象,并僅在需要時(shí)將它們轉(zhuǎn)換為文件引用URL。 基于路徑的URL更易于操作,更易于調(diào)試,并且通常是NSFileManager等類的首選。 文件引用URL的一個(gè)優(yōu)點(diǎn)是,當(dāng)您的應(yīng)用程序運(yùn)行時(shí),它們不如基于路徑的URL脆弱。 如果用戶在Finder中移動(dòng)文件,則任何引用該文件的基于路徑的URL都將立即變?yōu)闊o(wú)效,并且必須更新到新路徑。 但是,只要文件移動(dòng)到同一磁盤(pán)上的另一個(gè)位置,其唯一ID就不會(huì)更改,并且任何文件引用URL仍然有效。

Important: Although they are safe to use while your app is running, file reference URLs are not safe to store and reuse between launches of your app because a file’s ID may change if the system is rebooted. If you want to store the location of a file persistently between launches of your app, create a bookmark as described in Locating Files Using Bookmarks.

  • 重要提示:雖然在應(yīng)用程序運(yùn)行時(shí)可以安全使用它們,但是文件引用URL在應(yīng)用程序啟動(dòng)之間存儲(chǔ)和重用是不安全的,因?yàn)槿绻到y(tǒng)重新啟動(dòng),文件ID可能會(huì)更改。 如果要在啟動(dòng)應(yīng)用程序之間持久存儲(chǔ)文件的位置,請(qǐng)按照使用書(shū)簽查找文件中所述創(chuàng)建書(shū)簽。

Of course, there are still times when you might need to use strings to refer to a file. Fortunately, the NSURL class provides methods to convert path-based URLs to and from NSString objects. You might use a string-based path when presenting that path to the user or when calling a system routine that accepts strings instead of URLs. The conversion between NSURL objects and NSString objects is done using the NSURL class’s method absoluteString.

  • 當(dāng)然,有時(shí)您可能需要使用字符串來(lái)引用文件。 幸運(yùn)的是,NSURL類提供了將基于路徑的URL轉(zhuǎn)換為NSString對(duì)象和從NSString對(duì)象轉(zhuǎn)換的方法。 在向用戶顯示該路徑或調(diào)用接受字符串而不是URL的系統(tǒng)例程時(shí),您可以使用基于字符串的路徑。 NSURL對(duì)象和NSString對(duì)象之間的轉(zhuǎn)換是使用NSURL類的方法absoluteString完成的。

Because NSURL and NSString describe only the location of a file or directory, you can create them before the actual file or directory exists. Neither class attempts to validate the actual existence of the file or directory you specify. In fact, you must create the path to a nonexistent file or directory before you can create it on disk.

  • 因?yàn)?code>NSURL和NSString只描述文件或目錄的位置,所以可以在實(shí)際文件或目錄存在之前創(chuàng)建它們。 這兩個(gè)類都不會(huì)嘗試驗(yàn)證您指定的文件或目錄的實(shí)際存在。 實(shí)際上,必須先創(chuàng)建不存在的文件或目錄的路徑,然后才能在磁盤(pán)上創(chuàng)建它。

If you have an NSURL object that refers to an actual file or directory on disk, and you want to get the user visible name of the volume on which it resides, you use the method getResourceValue:forKey:error: in a two step process:
如果您有一個(gè)NSURL對(duì)象引用磁盤(pán)上的實(shí)際文件或目錄,并且您希望獲取其所在卷的用戶可見(jiàn)名稱,則使用方法getResourceValue:forKey:error:分兩步執(zhí)行:

  • Use the NSURLVolumeURLKey constant to obtain the volume URL from the resource URL.

    • 使用NSURLVolumeURLKey常量從資源URL獲取卷URL。
  • Use the NSURLLocalizedNameKey constant to obtain the user visible volume name from the volume URL.

    • 使用NSURLLocalizedNameKey常量從卷URL獲取用戶可見(jiàn)的卷名。

Use the NSURLLocalizedNameKey constant rather than the NSURLNameKey constant. Using NSURLNameKey returns the name of the volume in the file system, which may not be the same as the user visible name. Listing 2-1 demonstrates this process for the current user’s home directory.

  • 使用NSURLLocalizedNameKey常量而不是NSURLNameKey常量。 使用NSURLNameKey返回文件系統(tǒng)中卷的名稱,該名稱可能與用戶可見(jiàn)名稱不同。 清單2-1演示了當(dāng)前用戶主目錄的這個(gè)過(guò)程。

Listing 2-1 Obtaining the user visible volume name for a resource URL

NSURL *url = [NSURL fileURLWithPath:NSHomeDirectory()];
NSURL *volumeURL = nil;
NSString *volumeName = nil;
if ([url getResourceValue:&volumeURL forKey:NSURLVolumeURLKey error:nil]) {
    if ([volumeURL getResourceValue:&volumeName forKey:NSURLLocalizedNameKey error:nil]) {
        NSLog(@"The volume name is: %@", volumeName);
    }
}

For more information about the methods you use to create and manipulate URLs and strings, see NSURL Class Reference and NSString Class Reference.

  • 有關(guān)用于創(chuàng)建和操作URL和字符串的方法的詳細(xì)信息,請(qǐng)參閱NSURL類參考和NSString類參考。

Locating Items in the File System

  • 在文件系統(tǒng)中查找項(xiàng)目

Before you can access a file or directory, you need to know its location. There are several ways to locate files and directories:

  • 在您可以訪問(wèn)文件或目錄之前,您需要知道它的位置。 有幾種方法可以找到文件和目錄:
  • Find the file yourself. 自己查找文件。

  • Ask the user to specify a location. 要求用戶指定位置。

  • Locating files in the standard system directories, in both sandboxed and non-sandboxed apps. 在沙盒和非沙盒應(yīng)用程序中查找標(biāo)準(zhǔn)系統(tǒng)目錄中的文件。

  • Using bookmarks.使用書(shū)簽。

The file systems of iOS and macOS impose specific guidelines on where you should place files, so most of the items your app creates or uses should be stored in a well-known place. Both systems provide interfaces for locating items in such well-known places, and your app can use these interfaces to locate items and build paths to specific files. An app should prompt the user to specify the location of a file or directory only in a limited number of situations that are described in Using the Open and Save Panels.

  • iOS和macOS的文件系統(tǒng)對(duì)應(yīng)放置文件的位置強(qiáng)加了特定的指導(dǎo),因此應(yīng)用程序創(chuàng)建或使用的大多數(shù)項(xiàng)目都應(yīng)存儲(chǔ)在一個(gè)眾所周知的地方。 兩個(gè)系統(tǒng)都提供用于在這些眾所周知的地方定位項(xiàng)目的界面,您的應(yīng)用程序可以使用這些界面來(lái)查找項(xiàng)目并構(gòu)建指向特定文件的路徑。 應(yīng)用程序應(yīng)提示用戶僅在有限數(shù)量的情況下指定文件或目錄的位置,這些情況在使用“打開(kāi)”和“保存”面板中進(jìn)行了描述。

Asking the User to Locate an Item 要求用戶找到一個(gè)項(xiàng)目

In macOS, user interactions with the file system should always be through the standard Open and Save panels. Because these panels involve interrupting the user, use them only in a limited number of situations:

  • 在macOS中,用戶與文件系統(tǒng)的交互應(yīng)始終通過(guò)標(biāo)準(zhǔn)的“打開(kāi)”和“保存”面板。 由于這些面板涉及中斷用戶,因此僅在有限的情況下使用它們:
  • To open user documents 打開(kāi)用戶文檔

  • To ask the user where to save a new document 詢問(wèn)用戶保存新文檔的位置

  • To associate user files (or directories of files) with an open window 將用戶文件(或文件目錄)與打開(kāi)的窗口相關(guān)聯(lián)

Never use the Open and Save panels to access any files that your app created and uses internally. Support files, caches, and app-generated data files should be placed in one of the standard directories dedicated to app-specific files.

  • 切勿使用“打開(kāi)”和“保存”面板訪問(wèn)應(yīng)用在內(nèi)部創(chuàng)建和使用的任何文件。 支持文件,緩存和應(yīng)用程序生成的數(shù)據(jù)文件應(yīng)放在專用于特定于應(yīng)用程序的文件的標(biāo)準(zhǔn)目錄之一中。

For information on how to present and customize the Open and Save panels, see Using the Open and Save Panels.

Locating Items in Your App Bundle

  • 在應(yīng)用程序包中找到項(xiàng)目

Apps that need to locate resource files inside their bundle directory (or inside another known bundle) must do so using an NSBundle object. Bundles eliminate the need for your app to remember the location of individual files by organizing those files in a specific way. The methods of the NSBundle class understand that organization and use it to locate your app’s resources on demand. The advantage of this technique is that you can generally rearrange the contents of your bundle without rewriting the code you use to access it. Bundles also take advantage of the current user’s language settings to locate an appropriately localized version of a resource file.

  • 需要在其捆綁目錄(或其他已知捆綁包內(nèi))中找到資源文件的應(yīng)用程序必須使用NSBundle對(duì)象執(zhí)行此操作。 通過(guò)以特定方式組織這些文件,捆綁包使您的應(yīng)用無(wú)需記住單個(gè)文件的位置。 NSBundle類的方法了解該組織并使用它來(lái)按需定位應(yīng)用程序的資源。 這種技術(shù)的優(yōu)點(diǎn)是,您通??梢灾匦屡帕欣壈膬?nèi)容,而無(wú)需重寫(xiě)用于訪問(wèn)它的代碼。 Bundles還利用當(dāng)前用戶的語(yǔ)言設(shè)置來(lái)查找資源文件的適當(dāng)本地化版本。

The following code shows how to retrieve a URL object for an image named MyImage.png that is located in the app’s main bundle. This code determines only the location of the file; it does not open the file. You would pass the returned URL to a method of the NSImage class to load the image from disk so that you could use it.

  • 以下代碼顯示如何檢索位于應(yīng)用程序主包中的名為MyImage.png的圖像的URL對(duì)象。 此代碼僅確定文件的位置; 它不會(huì)打開(kāi)文件。 您可以將返回的URL傳遞給NSImage類的方法,以從磁盤(pán)加載圖像,以便您可以使用它。
NSURL* url = [[NSBundle mainBundle] URLForResource:@"MyImage" withExtension:@"png"];

For more information about bundles, including how to locate items in a bundle, see Bundle Programming Guide. For specific information about loading and using resources in your app, see Resource Programming Guide.

  • 有關(guān)包的更多信息,包括如何在包中查找項(xiàng),請(qǐng)參閱“包編程指南”。 有關(guān)在應(yīng)用程序中加載和使用資源的特定信息,請(qǐng)參閱“資源編程指南”。

Locating Items in the Standard Directories

  • 在標(biāo)準(zhǔn)目錄中查找項(xiàng)目

When you need to locate a file in one of the standard directories, use the system frameworks to locate the directory first and then use the resulting URL to build a path to the file. The Foundation framework includes several options for locating the standard system directories. By using these methods, the paths will be correct whether your app is sandboxed or not:
當(dāng)您需要在其中一個(gè)標(biāo)準(zhǔn)目錄中找到文件時(shí),請(qǐng)使用系統(tǒng)框架首先找到該目錄,然后使用生成的URL構(gòu)建該文件的路徑。 Foundation框架包括幾個(gè)用于查找標(biāo)準(zhǔn)系統(tǒng)目錄的選項(xiàng)。 通過(guò)使用這些方法,無(wú)論您的應(yīng)用是否為沙盒,路徑都是正確的:

  • The URLsForDirectory:inDomains: method of the NSFileManager class returns a directory’s location packaged in an NSURL object. The directory to search for is an NSSearchPathDirectory constant. These constants provide URLs for the user’s home directory, as well as most of the standard directories.

    • NSFileManager類的URLForDirectory:inDomains:方法返回打包在NSURL對(duì)象中的目錄位置。 要搜索的目錄是NSSearchPathDirectory常量。 這些常量為用戶的主目錄以及大多數(shù)標(biāo)準(zhǔn)目錄提供URL。
  • The NSSearchPathForDirectoriesInDomains function behaves like the URLsForDirectory:inDomains: method but returns the directory’s location as a string-based path. Use the URLsForDirectory:inDomains: method instead.

    • NSSearchPathForDirectoriesInDomains函數(shù)的行為類似于URLForDirectory:inDomains:方法,但返回目錄的位置作為基于字符串的路徑。 請(qǐng)改用URLForDirectory:inDomains:方法。
  • The NSHomeDirectory function returns the path to either the user’s or app’s home directory. (Which home directory is returned depends on the platform and whether the app is in a sandbox.) When an app is sandboxed the home directory points to the app’s sandbox, otherwise it points to the User’s home directory on the file system. If constructing a file to a subdirectory of a user’s home directory, consider using the URLsForDirectory:inDomains: method instead.

    • NSHomeDirectory函數(shù)返回用戶或應(yīng)用程序主目錄的路徑。 (返回哪個(gè)主目錄取決于平臺(tái)以及應(yīng)用程序是否位于沙箱中。)當(dāng)應(yīng)用程序?yàn)樯诚鋾r(shí),主目錄指向應(yīng)用程序的沙箱,否則它指向文件系統(tǒng)上的用戶主目錄。 如果將文件構(gòu)造到用戶主目錄的子目錄,請(qǐng)考慮使用URLForDirectory:inDomains:方法。

You can use the URL or path-based string you receive from the preceding routines to build new objects with the locations of the files you want. Both the NSURL and NSString classes provide path-related methods for adding and removing path components and making changes to the path in general. Listing 2-2 shows an example that searches for the standard Application Support directory and creates a new URL for a directory containing the app’s data files.

  • 您可以使用從前面的例程接收的URL或基于路徑的字符串來(lái)構(gòu)建具有所需文件位置的新對(duì)象。 NSURL和NSString類都提供了與路徑相關(guān)的方法,用于添加和刪除路徑組件以及對(duì)路徑進(jìn)行一般更改。 清單2-2顯示了一個(gè)示例,該示例搜索標(biāo)準(zhǔn)Application Support目錄并為包含應(yīng)用程序數(shù)據(jù)文件的目錄創(chuàng)建新URL。

Listing 2-2 Creating a URL for an item in the app support directory

- (NSURL*)applicationDataDirectory {
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSArray* possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
                                 inDomains:NSUserDomainMask];
    NSURL* appSupportDir = nil;
    NSURL* appDirectory = nil;

    if ([possibleURLs count] >= 1) {
        // Use the first directory (if multiple are returned)
        appSupportDir = [possibleURLs objectAtIndex:0];
    }

    // If a valid app support directory exists, add the
    // app's bundle ID to it to specify the final directory.
    if (appSupportDir) {
        NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
        appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
    }
    return appDirectory;
}

Locating Files Using Bookmarks

If you want to save the location of a file persistently, use the bookmark capabilities of NSURL. A bookmark is an opaque data structure, enclosed in an NSDataobject, that describes the location of a file. Whereas path- and file reference URLs are potentially fragile between launches of your app, a bookmark can usually be used to re-create a URL to a file even in cases where the file was moved or renamed.

  • 如果要持久保存文件的位置,請(qǐng)使用NSURL的書(shū)簽功能。 書(shū)簽是一個(gè)不透明的數(shù)據(jù)結(jié)構(gòu),包含在NSDataobject中,用于描述文件的位置。 雖然路徑和文件引用URL在您的應(yīng)用程序啟動(dòng)之間可能很脆弱,但即使在文件被移動(dòng)或重命名的情況下,通常也可以使用書(shū)簽重新創(chuàng)建文件的URL。

To create a bookmark for an existing URL, use the bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error: method of NSURL. Specifying the NSURLBookmarkCreationSuitableForBookmarkFile option creates an NSData object suitable for saving to disk. Listing 2-3 shows a simple example implementation that uses this method to create a bookmark data object.

  • 要為現(xiàn)有URL創(chuàng)建書(shū)簽,請(qǐng)使用bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error:NSURL的方法。 指定NSURLBookmarkCreationSuitableForBookmarkFile選項(xiàng)會(huì)創(chuàng)建適合保存到磁盤(pán)的NSData對(duì)象。 清單2-3顯示了一個(gè)使用此方法創(chuàng)建書(shū)簽數(shù)據(jù)對(duì)象的簡(jiǎn)單示例實(shí)現(xiàn)。

Listing 2-3 Converting a URL to a persistent form

- (NSData*)bookmarkForURL:(NSURL*)url {
    NSError* theError = nil;
    NSData* bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationSuitableForBookmarkFile
                                            includingResourceValuesForKeys:nil
                                            relativeToURL:nil
                                            error:&theError];
    if (theError || (bookmark == nil)) {
        // Handle any errors.
        return nil;
    }
    return bookmark;
}

If you write the persistent bookmark data to disk using the writeBookmarkData:toURL:options:error: method of NSURL, what the system creates on disk is an alias file. Aliases are similar to symbolic links but are implemented differently. Normally, users create aliases from the Finder when they want to create links to files elsewhere on the system.

  • 如果使用writeBookmarkData:toURL:options:error:NSURL方法將持久書(shū)簽數(shù)據(jù)寫(xiě)入磁盤(pán),則系統(tǒng)在磁盤(pán)上創(chuàng)建的是別名文件。 別名類似于符號(hào)鏈接,但實(shí)現(xiàn)方式不同。 通常,用戶在想要?jiǎng)?chuàng)建指向系統(tǒng)其他位置的文件的鏈接時(shí),可以從Finder創(chuàng)建別名。

To transform a bookmark data object back into a URL, use the URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error: method of NSURL. Listing 2-4 shows the process for converting a bookmark back into a URL.

  • 要將書(shū)簽數(shù)據(jù)對(duì)象轉(zhuǎn)換回URL,請(qǐng)使用URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:NSURL的方法。 清單2-4顯示了將書(shū)簽轉(zhuǎn)換回URL的過(guò)程。

Listing 2-4 Returning a persistent bookmark to its URL form

- (NSURL*)urlForBookmark:(NSData*)bookmark {
    BOOL bookmarkIsStale = NO;
    NSError* theError = nil;
    NSURL* bookmarkURL = [NSURL URLByResolvingBookmarkData:bookmark
                                            options:NSURLBookmarkResolutionWithoutUI
                                            relativeToURL:nil
                                            bookmarkDataIsStale:&bookmarkIsStale
                                            error:&theError];
 
    if (bookmarkIsStale || (theError != nil)) {
        // Handle any errors
        return nil;
    }
    return bookmarkURL;
}

The Core Foundation framework provides a set of C-based functions that parallel the bookmark interface provided by NSURL. For more information about using those functions, see CFURL Reference.

  • Core Foundation框架提供了一組基于C的函數(shù),這些函數(shù)與NSURL提供的書(shū)簽界面并行。 有關(guān)使用這些函數(shù)的更多信息,請(qǐng)參閱CFURL參考。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Enumerating the Contents of a Directory 枚舉目錄的內(nèi)容 To discov...
    ngugg閱讀 408評(píng)論 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,855評(píng)論 0 10
  • 最近心很煩,不得不寫(xiě)點(diǎn)什么發(fā)個(gè)小牢騷… 我特別喜歡工作,一直都是,很愿意跟小伙伴們一起頭腦風(fēng)暴做出產(chǎn)品熬夜上線這樣...
    keiko閱讀 291評(píng)論 0 0
  • 王晨一月第一次讀書(shū)打卡,我今天看的書(shū)是動(dòng)物系列小說(shuō)《雪域豹影》。 我最喜歡的一句話是:狂風(fēng)驟雨中,他用...
    王楊晨閱讀 202評(píng)論 0 0
  • 堅(jiān)持到底,才能笑到最后。人可以打敗自己,也可以成全自己。沒(méi)有人知道下一秒會(huì)發(fā)生什么,只要這一秒不放棄,下一秒就有可...
    清澈與明亮閱讀 233評(píng)論 0 0

友情鏈接更多精彩內(nèi)容