美文网首页
Accessing Files and Directories(

Accessing Files and Directories(

作者: ngugg | 来源:发表于2018-10-29 11:52 被阅读5次

    相关链接:
    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.

    • 在打开文件之前,首先必须在文件系统中找到它。 系统框架提供了许多例程来获取对许多知名目录的引用,例如Library目录及其内容。 您还可以通过从已知目录名构建URL或基于字符串的路径来手动指定位置。

    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.

    • 当您知道文件的位置时,您就可以开始规划访问它的最佳方式。 根据文件类型,您可能有多个选项。 对于已知的文件类型,通常使用内置系统例程来读取或写入文件内容,并为您提供可以使用的对象。 对于自定义文件类型,您可能需要自己读取原始文件数据。

    Choose the Right Way to Access Files

    • 选择正确的方式来访问文件
      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.
    • 虽然您可以打开任何文件并将其内容作为字节流读取,但这样做并不总是正确的选择。 macOS和iOS提供内置支持,可以更轻松地打开多种类型的标准文件格式(如文本文件,图像,声音和属性列表)。 对于这些标准文件格式,请使用更高级别的选项来读取和写入文件内容。 表2-1列出了系统支持的常用文件类型以及有关如何访问它们的信息。

    Table 2-1 File types with specialized routines

    • 具有专门例程的文件类型
    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.
    • 应用程序使用资源文件来存储独立于使用它的代码的数据。 资源文件通常用于存储可本地化的内容,例如字符串和图像。 从资源文件读取数据的过程取决于资源类型。

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

    • 有关如何读取资源文件内容的信息,请参阅“资源编程指南”。
    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字符的非结构化序列。 您通常将文本文件的内容加载到NSString对象中,但也可以读取和写入文本文件作为原始字符流。

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

    • 有关使用NSString类从文件加载文本的信息,请参阅“字符串编程指南”。
    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.
    • 结构化数据文件通常由使用一组特殊字符排列的基于字符串的数据组成。

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

    • 有关解析XML的信息,请参阅“事件驱动的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.
    • 存档是一种文件格式,用于存储应用程序运行时对象的持久版本。 归档程序对象将对象的状态编码为可以一次写入磁盘的字节流。 unarchiver反转进程,使用字节流重新创建对象并将其恢复到以前的状态。

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

    • 归档通常是为文档或其他数据文件实现自定义二进制文件格式的便捷替代方法。

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

    • 有关如何创建和读取存档文件的信息,请参阅存档和序列化编程指南。
    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.
    • 文件包是一个目录,它包含任意数量的自定义数据文件,但它们就像是单个文件一样呈现给用户。 应用程序可以使用文件包来实现包含多个不同文件的复杂文件格式,或者混合使用不同类型的文件。 例如,如果文件格式包含二进制数据文件和一个或多个图像,视频或音频文件,则可以使用文件包。 您可以使用NSFileWrapper对象访问文件包的内容,如使用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提供了一个结构化的环境,用于存储代码和该代码使用的资源。 大多数情况下,您不使用包本身,而是使用其内容。 但是,您可以根据需要找到捆绑包并获取有关它们的信息。

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

    • 有关捆绑包以及如何访问它们的信息,请参阅捆绑包编程指南
    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.
    • 使用插件和共享库的应用程序需要能够加载该项目的关联代码以利用其功能。

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

    • 有关如何将代码资源加载到内存的信息,请参阅代码加载编程主题。

    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.

    • 在标准文件格式并不是很高效的情况下,您可以创建自己的自定义文件格式。 在读取和写入自定义文件的内容时,您可以将数据作为字节流读取和写入,并将这些字节应用于应用程序的文件相关数据结构。 您可以完全控制如何读取和写入字节以及如何管理与文件相关的数据结构。 有关读取和写入使用自定义文件格式的文件的技术的详细信息,请参阅无文件协调器的读取和写入文件的技术。

    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类有许多与路径创建相关的方法,但URL提供了一种更健壮的方法来定位文件和目录。 对于也使用网络资源的应用程序,URL还意味着您可以使用一种类型的对象来管理位于本地文件系统或网络服务器上的项目。

    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进行操作。 NSURL类与CFURLReftype进行免费桥接,这意味着您可以在代码中交替使用它们。 有关如何使用Core Foundation创建和操作URL的更多信息,请参阅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.

    • 对于大多数URL,您可以通过使用适当的NSURL方法将目录和文件名连接在一起来构建URL,直到获得该项的路径。 以这种方式构建的URL称为基于路径的URL,因为它存储遍历目录层次结构以查找项目所需的名称。 (您还可以通过将目录和文件名连接在一起来构建基于字符串的路径,结果的格式与NSURL类使用的格式略有不同。)除了基于路径的URL,您还可以创建文件引用 URL,使用唯一ID标识文件或目录的位置。

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

    • 以下所有条目都是对用户的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方法创建URL对象,并仅在需要时将它们转换为文件引用URL。 基于路径的URL更易于操作,更易于调试,并且通常是NSFileManager等类的首选。 文件引用URL的一个优点是,当您的应用程序运行时,它们不如基于路径的URL脆弱。 如果用户在Finder中移动文件,则任何引用该文件的基于路径的URL都将立即变为无效,并且必须更新到新路径。 但是,只要文件移动到同一磁盘上的另一个位置,其唯一ID就不会更改,并且任何文件引用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.

    • 重要提示:虽然在应用程序运行时可以安全使用它们,但是文件引用URL在应用程序启动之间存储和重用是不安全的,因为如果系统重新启动,文件ID可能会更改。 如果要在启动应用程序之间持久存储文件的位置,请按照使用书签查找文件中所述创建书签。

    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.

    • 当然,有时您可能需要使用字符串来引用文件。 幸运的是,NSURL类提供了将基于路径的URL转换为NSString对象和从NSString对象转换的方法。 在向用户显示该路径或调用接受字符串而不是URL的系统例程时,您可以使用基于字符串的路径。 NSURL对象和NSString对象之间的转换是使用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.

    • 因为NSURLNSString只描述文件或目录的位置,所以可以在实际文件或目录存在之前创建它们。 这两个类都不会尝试验证您指定的文件或目录的实际存在。 实际上,必须先创建不存在的文件或目录的路径,然后才能在磁盘上创建它。

    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:
    如果您有一个NSURL对象引用磁盘上的实际文件或目录,并且您希望获取其所在卷的用户可见名称,则使用方法getResourceValue:forKey:error:分两步执行:

    • 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获取用户可见的卷名。

    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返回文件系统中卷的名称,该名称可能与用户可见名称不同。 清单2-1演示了当前用户主目录的这个过程。

    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.

    • 有关用于创建和操作URL和字符串的方法的详细信息,请参阅NSURL类参考和NSString类参考。

    Locating Items in the File System

    • 在文件系统中查找项目

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

    • 在您可以访问文件或目录之前,您需要知道它的位置。 有几种方法可以找到文件和目录:
    • 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. 在沙盒和非沙盒应用程序中查找标准系统目录中的文件。

    • Using bookmarks.使用书签。

    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的文件系统对应放置文件的位置强加了特定的指导,因此应用程序创建或使用的大多数项目都应存储在一个众所周知的地方。 两个系统都提供用于在这些众所周知的地方定位项目的界面,您的应用程序可以使用这些界面来查找项目并构建指向特定文件的路径。 应用程序应提示用户仅在有限数量的情况下指定文件或目录的位置,这些情况在使用“打开”和“保存”面板中进行了描述。

    Asking the User to Locate an Item 要求用户找到一个项目

    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中,用户与文件系统的交互应始终通过标准的“打开”和“保存”面板。 由于这些面板涉及中断用户,因此仅在有限的情况下使用它们:
    • To open user documents 打开用户文档

    • To ask the user where to save a new document 询问用户保存新文档的位置

    • To associate user files (or directories of files) with an open window 将用户文件(或文件目录)与打开的窗口相关联

    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.

    • 切勿使用“打开”和“保存”面板访问应用在内部创建和使用的任何文件。 支持文件,缓存和应用程序生成的数据文件应放在专用于特定于应用程序的文件的标准目录之一中。

    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

    • 在应用程序包中找到项目

    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.

    • 需要在其捆绑目录(或其他已知捆绑包内)中找到资源文件的应用程序必须使用NSBundle对象执行此操作。 通过以特定方式组织这些文件,捆绑包使您的应用无需记住单个文件的位置。 NSBundle类的方法了解该组织并使用它来按需定位应用程序的资源。 这种技术的优点是,您通常可以重新排列捆绑包的内容,而无需重写用于访问它的代码。 Bundles还利用当前用户的语言设置来查找资源文件的适当本地化版本。

    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.

    • 以下代码显示如何检索位于应用程序主包中的名为MyImage.png的图像的URL对象。 此代码仅确定文件的位置; 它不会打开文件。 您可以将返回的URL传递给NSImage类的方法,以从磁盘加载图像,以便您可以使用它。
    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.

    • 有关包的更多信息,包括如何在包中查找项,请参阅“包编程指南”。 有关在应用程序中加载和使用资源的特定信息,请参阅“资源编程指南”。

    Locating Items in the Standard Directories

    • 在标准目录中查找项目

    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:
    当您需要在其中一个标准目录中找到文件时,请使用系统框架首先找到该目录,然后使用生成的URL构建该文件的路径。 Foundation框架包括几个用于查找标准系统目录的选项。 通过使用这些方法,无论您的应用是否为沙盒,路径都是正确的:

    • 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对象中的目录位置。 要搜索的目录是NSSearchPathDirectory常量。 这些常量为用户的主目录以及大多数标准目录提供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函数的行为类似于URLForDirectory:inDomains:方法,但返回目录的位置作为基于字符串的路径。 请改用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函数返回用户或应用程序主目录的路径。 (返回哪个主目录取决于平台以及应用程序是否位于沙箱中。)当应用程序为沙箱时,主目录指向应用程序的沙箱,否则它指向文件系统上的用户主目录。 如果将文件构造到用户主目录的子目录,请考虑使用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或基于路径的字符串来构建具有所需文件位置的新对象。 NSURL和NSString类都提供了与路径相关的方法,用于添加和删除路径组件以及对路径进行一般更改。 清单2-2显示了一个示例,该示例搜索标准Application Support目录并为包含应用程序数据文件的目录创建新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.

    • 如果要持久保存文件的位置,请使用NSURL的书签功能。 书签是一个不透明的数据结构,包含在NSDataobject中,用于描述文件的位置。 虽然路径和文件引用URL在您的应用程序启动之间可能很脆弱,但即使在文件被移动或重命名的情况下,通常也可以使用书签重新创建文件的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.

    • 要为现有URL创建书签,请使用bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error:NSURL的方法。 指定NSURLBookmarkCreationSuitableForBookmarkFile选项会创建适合保存到磁盘的NSData对象。 清单2-3显示了一个使用此方法创建书签数据对象的简单示例实现。

    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方法将持久书签数据写入磁盘,则系统在磁盘上创建的是别名文件。 别名类似于符号链接,但实现方式不同。 通常,用户在想要创建指向系统其他位置的文件的链接时,可以从Finder创建别名。

    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.

    • 要将书签数据对象转换回URL,请使用URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:NSURL的方法。 清单2-4显示了将书签转换回URL的过程。

    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的函数,这些函数与NSURL提供的书签界面并行。 有关使用这些函数的更多信息,请参阅CFURL参考。

    相关文章

      网友评论

          本文标题:Accessing Files and Directories(

          本文链接:https://www.haomeiwen.com/subject/msyltqtx.html