String Programming Guide

String Representations of File Paths

NSString provides a rich set of methods for manipulating strings as file-system paths. You can extract a path’s directory, filename, and extension, expand a tilde expression (such as “~me”) or create one for the user’s home directory, and clean up paths containing symbolic links, redundant slashes, and references to “.” (current directory) and “..” (parent directory).

Note: Where possible, you should use instances of NSURL to represent paths—the operating system deals with URLs more efficiently than with string representations of paths.

Representing a Path

NSString represents paths generically with ‘/’ as the path separator and ‘.’ as the extension separator. Methods that accept strings as path arguments convert these generic representations to the proper system-specific form as needed. On systems with an implicit root directory, absolute paths begin with a path separator or with a tilde expression (“~/...” or “~user/...”). Where a device must be specified, you can do that yourself—introducing a system dependency—or allow the string object to add a default device.

You can create a standardized representation of a path using stringByStandardizingPath. This performs a number of tasks including:

Expansion of an initial tilde expression;

Reduction of empty components and references to the current directory (“//” and “/./”) to single path separators;

In absolute paths, resolution of references to the parent directory (“..”) to the real parent directory;

for example:

NSString *path = @"/usr/bin/./grep";

NSString *standardizedPath = [path stringByStandardizingPath];

// standardizedPath: /usr/bin/grep

path = @"~me";

standardizedPath = [path stringByStandardizingPath];

// standardizedPath (assuming conventional naming scheme): /Users/Me

path = @"/usr/include/objc/..";

standardizedPath = [path stringByStandardizingPath];

// standardizedPath: /usr/include

path = @"/private/usr/include";

standardizedPath = [path stringByStandardizingPath];

// standardizedPath: /usr/include

User Directories

The following examples illustrate how you can use NSString’s path utilities and other Cocoa functions to get the user directories.