Mac OS X Reference Library Apple Developer Connection spyglass button

NSFileManager Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in Mac OS X v10.0 and later.
Companion guide
Declared in
NSFileManager.h
Related sample code

Overview

NSFileManager enables you to perform many generic file-system operations and insulates an application from the underlying file system.

In Mac OS X v 10.5 and later you are no longer restricted to using this class as a singleton. Instances of NSFileManager are considered thread-safe when created using [[NSFileManager alloc] init].

Tasks

Creating a File Manager

Moving an Item

Copying an Item

Removing an Item

Creating an Item

Linking an Item

Symbolic-Link Operations

Handling File Operations

The methods described in this section are to be implemented by the callback handler passed to several methods of NSFileManager. These methods have been deprecated as of Mac OS X 10.5. Use the corresponding delegate methods instead.

Getting and Comparing File Contents

Discovering Directory Contents

Determining Access to Files

Getting and Setting Attributes

Getting Representations of File Paths

Managing the Delegate

Managing the Current Directory

Locating System Directories

Safely Replace a File

Class Methods

defaultManager

Returns the default NSFileManager object for the file system.

+ (NSFileManager *)defaultManager

Return Value

The default NSFileManager object for the file system.

Discussion

This will always return the same instance of the file manager. The returned object is not thread safe.

In Mac OS X v 10.5 and later you are no longer restricted to using this class as a singleton. You can allocate and init instances of this class as you would any other. In the case that you use the [[NSFileManager alloc] init] methodology, the resulting NSFileManager is thread safe.

Availability
Related Sample Code
Declared In
NSFileManager.h

Instance Methods

attributesOfFileSystemForPath:error:

Returns a dictionary that describes the attributes of the mounted file system on which a given path resides.

- (NSDictionary *)attributesOfFileSystemForPath:(NSString *)path error:(NSError **)error

Parameters
path

Any pathname within the mounted file system.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

An NSDictionary object that describes the attributes of the mounted file system on which path resides. See “File-System Attribute Keys” for a description of the keys available in the dictionary.

Discussion

This method does not traverse a terminal symbolic link.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Declared In
NSFileManager.h

attributesOfItemAtPath:error:

Returns the attributes of the item at a given path.

- (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error

Parameters
path

The path of a file or directory.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

An NSDictionary object that describes the attributes (file, directory, symlink, and so on) of the file specified by path. The keys in the dictionary are described in “File Attribute Keys”.

Special Considerations

As a convenience, NSDictionary provides a set of methods (declared as a category in NSFileManager.h) for quickly and efficiently obtaining attribute information from the returned dictionary: fileGroupOwnerAccountName, fileModificationDate, fileOwnerAccountName, filePosixPermissions, fileSize, fileSystemFileNumber, fileSystemNumber, and fileType.

In Mac OS X v 10.6 and earlier, if the last component of the path is a symbolic link (the value of the NSFileType key in the attributes dictionary is NSFileTypeSymbolicLink), it will be traversed. This behavior may change in a future version of the Mac OS X.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

changeCurrentDirectoryPath:

Changes the path of the current directory for the current process to a given path.

- (BOOL)changeCurrentDirectoryPath:(NSString *)path

Parameters
path

The path of the directory to which to change.

Return Value

YES if successful, otherwise NO.

Discussion

All relative pathnames refer implicitly to the current working directory. The current working directory is stored per process.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Declared In
NSFileManager.h

componentsToDisplayForPath:

Returns an array of NSString objects representing the user-visible components of a given path.

- (NSArray *)componentsToDisplayForPath:(NSString *)path

Parameters
path

A pathname.

Return Value

An array of NSString objects representing the user-visible (for the Finder, Open and Save panels, and so on) components of path. Returns nil if path does not exist.

Discussion

These components cannot be used for path operations and are only suitable for display to the user.

Availability
  • Available in Mac OS X v10.2 and later.
Related Sample Code
Declared In
NSFileManager.h

contentsAtPath:

Returns as an NSData object the contents of the file at at given path.

- (NSData *)contentsAtPath:(NSString *)path

Parameters
path

The path of a file.

Return Value

The contents of the file specified by path as an NSData object. If path specifies a directory, or if some other error occurs, returns nil.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Declared In
NSFileManager.h

contentsEqualAtPath:andPath:

Returns a Boolean value that indicates whether the files or directories in specified paths have the same contents.

- (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2

Parameters
path1

The path of a file or directory to compare with the contents of path2.

path2

The path of a file or directory to compare with the contents of path1.

Return Value

YES if file or directory specified in path1 has the same contents as that specified in path2, otherwise NO.

Discussion

If path1 and path2 are directories, the contents are the list of files and subdirectories each contains—contents of subdirectories are also compared. For files, this method checks to see if they’re the same file, then compares their size, and finally compares their contents. This method does not traverse symbolic links, but compares the links themselves.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Declared In
NSFileManager.h

contentsOfDirectoryAtPath:error:

Returns the directories and files (including symbolic links) contained in a given directory.

- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error

Parameters
path

A path to a directory.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

An array of NSString objects identifying the directories and files (including symbolic links) contained in path. Returns an empty array if the directory exists but has no contents. Returns nil if the directory specified at path does not exist or there is some other error accessing it.

Discussion

The search is shallow and therefore does not return the contents of any subdirectories. This returned array does not contain strings for the current directory (“.”), parent directory (“..”), or resource forks (begin with “._”) and does not traverse symbolic links.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:

Returns the contents of a directory.

- (NSArray *)contentsOfDirectoryAtURL:(NSURL *)url includingPropertiesForKeys:(NSArray *)keys options:(NSDirectoryEnumerationOptions)mask error:(NSError **)error

Parameters
url

The location of the directory for which you want an enumeration.

keys

On input, an array of property keys for which you would like the corresponding values. These specify the file properties that are pre-fetched for each of the files in the directory.

When an array is specified for this parameter, the specified property values are pre-fetched and cached with each enumerated URL. The property keys that can be requested are listed in he property keys that can be requested are listed in Common File System Resource Keys)

mask

Options for the enumeration. Because this method only performs shallow enumeration only the NSDirectoryEnumerationSkipsHiddenFiles option should be used.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

An array of NSURL objects identifying the directory entries. If the directory contains no entries, this method returns an empty array. If an error occurs, returns nil after setting error to an NSError object that describes the reason why the directory could not be enumerated.

Discussion

This method always does a shallow enumeration of the specified directory (i.e. it always acts as if NSDirectoryEnumerationSkipsSubdirectoryDescendants has been specified). If you need to perform a deep enumeration, use enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:].

The order of the files within the returned array is undefined.

Availability
  • Available in Mac OS X v10.6 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

copyItemAtPath:toPath:error:

Copies the directory or file specified in a given path to a different location in the file system identified by another path.

- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error

Parameters
srcPath

The path of a file or directory.

dstPath

The path of a file or directory.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the operation was successful. If the operation is not successful, but the delegate returns YES from the fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: message, copyItemAtPath:toPath:error: also returns YES. Otherwise this method returns NO. The method also attempts to make the attributes of the directory or file at dstPath identical to srcPath, but ignores any failure at this attempt.

Discussion

If srcPath is a file, the method creates a file at dstPath that holds the exact contents of the original file (this includes BSD special files). If srcPath is a directory, the method creates a new directory at dstPath and recursively populates it with duplicates of the files and directories contained in srcPath, preserving all links. The file specified in srcPath must exist, while dstPath must not exist prior to the operation. When a file is being copied, the destination path must end in a filename—there is no implicit adoption of the source filename. Symbolic links are not traversed but are themselves copied. File or directory attributes—that is, metadata such as owner and group numbers, file permissions, and modification date—are also copied.

NSFileManager sends your delegate fileManager:shouldCopyItemAtPath:toPath: when it begins a copy operation. If the delegate returns YES, NSFileManager attempts to copy the item. If the delegate returns NO, the copyItemAtPath:toPath:error: function does not copy the item.

NSFileManager sends your delegate fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: when it encounters any error in processing. If the delegate returns YES, then NSFileManager proceeds as if no error had occurred. If it returns NO, the copyItemAtPath:toPath:error: function terminates and passes the error back in the error parameter.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

copyItemAtURL:toURL:error:

Copies the directory or file specified in a given URL to a different location in the file system identified by another URL.

- (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error

Parameters
srcURL

The URL of a file or directory.

dstURL

The URL of a file or directory.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the operation was successful. If the operation is not successful, but the delegate returns YES from the fileManager:shouldProceedAfterError:copyingItemAtURL:toURL: message, copyItemAtURL:toURL:error: also returns YES. Otherwise this method returns NO. The method also attempts to make the attributes of the directory or file at dstURL identical to srcURL, but ignores any failure at this attempt.

Discussion

If srcURL is a file, the method creates a file at dstURL that holds the exact contents of the original file (this includes BSD special files). If srcURL is a directory, the method creates a new directory at dstURL and recursively populates it with duplicates of the files and directories contained in srcURL, preserving all links. The file specified in srcURL must exist, while dstURL must not exist prior to the operation. When a file is being copied, the destination URL must end in a filename—there is no implicit adoption of the source filename. Symbolic links are not traversed but are themselves copied. File or directory attributes—that is, metadata such as owner and group numbers, file permissions, and modification date—are also copied.

NSFileManager sends your delegate fileManager:shouldCopyItemAtURL:toURL: when it begins a copy operation. If the delegate returns YES, NSFileManager attempts to copy the item. If the delegate returns NO, the copyItemAtURL:toURL:error: function does not copy the item.

NSFileManager sends your delegate fileManager:shouldProceedAfterError:copyingItemAtURL:toURL: when it encounters any error in processing. If the delegate returns YES, then NSFileManager proceeds as if no error had occurred. If it returns NO, the copyItemAtURL:toURL:error: function terminates and passes the error back in the error parameter.

Availability
  • Available in Mac OS X v10.6 and later.
See Also
Declared In
NSFileManager.h

createDirectoryAtPath:withIntermediateDirectories:attributes:error:

Creates a directory with given attributes at a specified path.

- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error

Parameters
path

The path at which to create the new directory. The directory to be created must not yet exist.

createIntermediates

If YES, then the method will also create any necessary intermediate directories; if NO, then the method fails if any parent of the directory to be created does not exist. In addition, if you pass NO for this parameter, the directory must not exist at the time this call is made.

attributes

The file attributes for the new directory. The attributes you can set are owner and group numbers, file permissions, and modification date. If you specify nil for attributes, the directory is created according to the umask of the process. The “Constants” section lists the global constants used as keys in the attributes dictionary. Some of the keys, such as NSFileHFSCreatorCode and NSFileHFSTypeCode, do not apply to directories.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the operation was successful, otherwise NO.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

createFileAtPath:contents:attributes:

Creates a file at a given path that has given attributes and contents.

- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)contents attributes:(NSDictionary *)attributes

Parameters
path

The path for the new file.

contents

The contents for the new file.

attributes

A dictionary that describes the attributes of the new file. The file attributes you can set are owner and group numbers, file permissions, and modification date. “File Attribute Keys” lists the global constants used as keys in the attributes dictionary. If you specify nil for attributes, the file is given a default set of attributes.

Return Value

YES if the operation was successful, otherwise NO.

Discussion

If a file already exists at path, then if the file can be overwritten (subject to user privileges) it will be.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

createSymbolicLinkAtPath:withDestinationPath:error:

Creates a symbolic link identified by a given path that refers to a given location.

- (BOOL)createSymbolicLinkAtPath:(NSString *)path withDestinationPath:(NSString *)destPath error:(NSError **)error

Parameters
path

The path for a symbolic link.

destPath

The path to which path should refer.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the operation is successful, otherwise NO. Returns NO if a file, directory, or symbolic link identical to path already exists.

Discussion

Creates a symbolic link identified by path that refers to the location destPath in the file system.

This method does not traverse a terminal symbolic link.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Declared In
NSFileManager.h

currentDirectoryPath

Returns the path of the program’s current directory.

- (NSString *)currentDirectoryPath

Return Value

The path of the program’s current directory. If the program’s current working directory isn’t accessible, returns nil.

Discussion

The string returned by this method is initialized to the current working directory; you can change the working directory by invoking changeCurrentDirectoryPath:.

Relative pathnames refer implicitly to the current directory. For example, if the current directory is /tmp, and the relative pathname reports/info.txt is specified, the resulting full pathname is /tmp/reports/info.txt.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

delegate

Returns the delegate for the receiver.

- (id)delegate

Return Value

The delegate for the receiver.

Availability
  • Available in Mac OS X v10.5 and later.
Declared In
NSFileManager.h

destinationOfSymbolicLinkAtPath:error:

Returns the path of the item pointed to by a symbolic link.

- (NSString *)destinationOfSymbolicLinkAtPath:(NSString *)path error:(NSError **)error

Parameters
path

The path of a file or directory.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

An NSString object containing the path of the directory or file to which the symbolic link path refers, or nil upon failure. If the symbolic link is specified as a relative path, that relative path is returned.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Declared In
NSFileManager.h

displayNameAtPath:

Returns the name of the file or directory at a given path in a localized form appropriate for presentation to the user.

- (NSString *)displayNameAtPath:(NSString *)path

Parameters
path

The path of a file or directory.

Return Value

The name of the file or directory at path in a localized form appropriate for presentation to the user. If there is no file or directory at path, or if an error occurs, returns path as is.

Discussion

The returned value is localized where appropriate. For example, if you have selected French as your preferred language, the following code fragment logs “Bibliothèque”:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
if ([paths count] > 0)
{
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *displayNameAtPath = [fileManager displayNameAtPath:documentsDirectory];
    NSLog(@"%@", displayNameAtPath);
}
Availability
  • Available in Mac OS X v10.1 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

enumeratorAtPath:

Creates and returns an NSDirectoryEnumerator object that enumerates the contents of the directory at a given path.

- (NSDirectoryEnumerator *)enumeratorAtPath:(NSString *)path

Parameters
path

The path of the directory to enumerate.

Return Value

An NSDirectoryEnumerator object that enumerates the contents of the directory at path.

If path is a filename, the method returns an enumerator object that enumerates no files—the first call to nextObject will return nil.

Discussion

Because the enumeration is deep—that is, it lists the contents of all subdirectories—this enumerator object is useful for performing actions that involve large file-system subtrees. This method does not resolve symbolic links encountered in the traversal process, nor does it recurse through them if they point to a directory.

This code fragment enumerates the subdirectories and files under a user’s Documents directory and processes all files with an extension of .doc:

NSString *file;
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:  @"Documents"];
NSDirectoryEnumerator *dirEnum =
    [[NSFileManager defaultManager] enumeratorAtPath:docsDir];
 
while (file = [dirEnum nextObject]) {
    if ([[file pathExtension] isEqualToString: @"doc"]) {
        [self scanDocument: [docsDir stringByAppendingPathComponent:file]];
    }
}

The NSDirectoryEnumerator class has methods for obtaining the attributes of the existing path and of the parent directory and for skipping descendants of the existing path.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:

Creates and returns a directory enumerator object that enumerates the contents of the directory at a given URL.

- (NSDirectoryEnumerator *)enumeratorAtURL:(NSURL *)url includingPropertiesForKeys:(NSArray *)keys options:(NSDirectoryEnumerationOptions)mask errorHandler:(BOOL (^)(NSURL *url, NSError *error))handler

Parameters
url

The location of the directory for which you want an enumeration.

keys

On input, an array of property keys for which you would like the corresponding values. On output, the property values corresponding to those keys. Specify NULL for this array if you do not want any property values. The property keys that can be requested are listed in Foundation/NSURL.h (see NSURL Class Reference).

When an array is specified for this parameter, the specified property values are pre-fetched and cached with each enumerated URL.

mask

Options for the enumeration. See “Directory Enumeration Options.”

handler

The optional 'errorHandler' block argument is invoked when an error occurs. Parameters to the block are the URL on which an error occurred and the error. When the error handler returns YES, enumeration continues if possible. Enumeration stops immediately when the error handler returns NO.

Return Value

An NSDirectoryEnumerator object that enumerates the contents of the directory at url. If url is a symbolic link, this method evaluates the link and returns an enumerator for the file or directory the link points to. If the link cannot be evaluated, the method returns nil.

If url is a filename, the method returns an enumerator object that enumerates no files—the first call to nextObject returns nil.

Discussion

Because the enumeration is deep—that is, it lists the contents of all subdirectories—this enumerator object is useful for performing actions that involve large file-system subtrees. If the method is passed a directory on which another file system is mounted (a mount point), it traverses the mount point. This method does not resolve symbolic links encountered in the traversal process, nor does it recurse through them if they point to a directory.

This code fragment enumerates the subdirectories and files under a user’s Documents directory and processes all files with an extension of .doc:

NSURL *url;
NSURL *docsDir = [[NSFileManager defaultManager]
                   initFileURLWithPath:([NSHomeDirectory()
                   stringByAppendingPathComponent:  @"Documents"])
                   keys:NULL mask:NULL handler:NULL];
NSDirectoryEnumerator *dirEnum =
    [[NSFileManager defaultManager] enumeratorAtURL:docsDir];
 
while (file = [dirEnum nextObject]) {
    if ([[file pathExtension] isEqualToString: @"doc"]) {
        [self scanDocument: [docsDir stringByAppendingPathComponent:file]];
    }
}

The NSDirectoryEnumerator class has methods for skipping descendants of the existing path and for returning the number of levels deep the current object is in the directory hierarchy being enumerated (where the directory passed to enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: is considered to be level 0).

Availability
  • Available in Mac OS X v10.6 and later.
See Also
Declared In
NSFileManager.h

fileExistsAtPath:

Returns a Boolean value that indicates whether a file or directory exists at a specified path.

- (BOOL)fileExistsAtPath:(NSString *)path

Parameters
path

The path of a file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath, or this method returns NO.

Return Value

YES if a file specified in path exists, otherwise NO. If the final element in path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file at the link destination.

Discussion

Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior in the case of file system race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle any error gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see Avoiding Race Conditions and Insecure File Operations in Secure Coding Guide.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

fileExistsAtPath:isDirectory:

Returns a Boolean value that indicates whether a file or directory exists at a specified path.

- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory

Parameters
path

The path of a file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath, or this method will return NO.

isDirectory

Upon return, contains YES if path is a directory or if the final path element is a symbolic link that points to a directory, otherwise contains NO. If path doesn’t exist, the return value is undefined. Pass NULL if you do not need this information.

Return Value

YES if there is a file or directory at path, otherwise NO. If the final element in path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file or directory at the link destination.

Discussion

If you need to further determine if path is a package, use the NSWorkspace method isFilePackageAtPath:.

This example gets an array that identifies the fonts in the user's fonts directory:

NSArray *subpaths;
BOOL isDir;
 
NSArray *paths = NSSearchPathForDirectoriesInDomains
                     (NSLibraryDirectory, NSUserDomainMask, YES);
 
if ([paths count] == 1) {
 
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *fontPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Fonts"];
 
    if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir) {
        subpaths = [fileManager subpathsAtPath:fontPath];
// ...
Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior in the case of file system race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle any error gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see Avoiding Race Conditions and Insecure File Operations in Secure Coding Guide.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

fileSystemRepresentationWithPath:

Returns a C-string representation of a given path that properly encodes Unicode strings for use by the file system.

- (const char *)fileSystemRepresentationWithPath:(NSString *)path

Parameters
path

A file path.

Return Value

A C-string representation of path that properly encodes Unicode strings for use by the file system.

Discussion

If you need the C string beyond the scope of your autorelease pool, you must copy it. This method raises an exception upon error. Use this method if your code calls system routines that expect C-string path arguments.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Declared In
NSFileManager.h

init

Returns an initialized NSFileManager instance.

- init

Return Value

An initialized NSFileManager instance.

Discussion

In Mac OS X v 10.5 and earlier sending the init message was undefined. In Mac OS X 10.6 and later it will initialize the receiver.

isDeletableFileAtPath:

Returns a Boolean value that indicates whether the invoking object appears able to delete a specified file.

- (BOOL)isDeletableFileAtPath:(NSString *)path

Parameters
path

A file path.

Return Value

YES if the invoking object appears able to delete the file specified in path, otherwise NO. If the file at path does not exist, this method returns NO.

Discussion

For a directory or file to be able to be deleted, either the parent directory of path must be writable or its owner must be the same as the owner of the application process. If path is a directory, every item contained in path must be able to be deleted.

This method does not traverse symbolic links.

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior in the case of file system race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle any error gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see Avoiding Race Conditions and Insecure File Operations in Secure Coding Guide.

Availability
  • Available in Mac OS X v10.0 and later.
Declared In
NSFileManager.h

isExecutableFileAtPath:

Returns a Boolean value that indicates whether the operating system appears able to execute a specified file.

- (BOOL)isExecutableFileAtPath:(NSString *)path

Parameters
path

A file path.

Return Value

YES if the operating system appears able to execute the file specified in path, otherwise NO. If the file at path does not exist, this method returns NO.

Discussion

This method traverses symbolic links. This method uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is executable.

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior in the case of file system race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle any error gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see Avoiding Race Conditions and Insecure File Operations in Secure Coding Guide.

Availability
  • Available in Mac OS X v10.0 and later.
Declared In
NSFileManager.h

isReadableFileAtPath:

Returns a Boolean value that indicates whether the invoking object appears able to read a specified file.

- (BOOL)isReadableFileAtPath:(NSString *)path

Parameters
path

A file path.

Return Value

YES if the invoking object appears able to read the file specified in path, otherwise NO. If the file at path does not exist, this method returns NO.

Discussion

This method traverses symbolic links. This method uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is readable.

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior in the case of file system race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle any error gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see Avoiding Race Conditions and Insecure File Operations in Secure Coding Guide.

Availability
  • Available in Mac OS X v10.0 and later.
Related Sample Code
Declared In
NSFileManager.h

isWritableFileAtPath:

Returns a Boolean value that indicates whether the invoking object appears able to write to a specified file.

- (BOOL)isWritableFileAtPath:(NSString *)path

Parameters
path

A file path.

Return Value

YES if the invoking object appears able to write to the file specified in path, otherwise NO. If the file at path does not exist, this method returns NO.

Discussion

This method traverses symbolic links. This method uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is writable.

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior in the case of file system race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle any error gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see Avoiding Race Conditions and Insecure File Operations in Secure Coding Guide.

Availability
  • Available in Mac OS X v10.0 and later.
Declared In
NSFileManager.h

linkItemAtPath:toPath:error:

Creates a hard link from a source to a destination identified by a path.

- (BOOL)linkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error

Parameters
srcPath

A path that identifies a source file.

The file or link specified by srcPath must exist. srcPath must not identify a directory.

dstPath

A path that identifies a destination file or directory on the same filesystem as srcPath.

The destination should not yet exist. The destination path must end in a filename; there is no implicit adoption of the source filename.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the link operation is successful. If the operation is not successful, but the delegate returns YES from the fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: message, linkItemAtPath:toPath:error: also returns YES. Otherwise this method returns NO.

Discussion

If pathname srcPath identifies a file, this method hard-links the file specified in dstPath to it.

Amongst other reasons (such as the disk being full, permissions problems, and so on), this method will fail if:

NSFileManager sends your delegate fileManager:shouldLinkItemAtPath:toPath: when it begins a hard-link operation. If the delegate returns YES, NSFileManager attempts to hard-link the item. If the delegate returns NO, the linkItemAtPath:toPath:error: function does not hard-link the item.

NSFileManager sends your delegate fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: when it encounters any error in processing. If the delegate returns YES, then NSFileManager proceeds as if no error had occurred. If it returns NO, the linkItemAtPath:toPath:error: function terminates and passes the error back in the error parameter.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Declared In
NSFileManager.h

linkItemAtURL:toURL:error:

Creates a hard link from a source to a destination identified by a URL.

- (BOOL)linkItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error

Parameters
srcURL

A URL that identifies a source file.

The file or link specified by srcURL must exist. srcURL must not identify a directory.

dstURL

A URL that identifies a destination file or directory on the same filesystem as srcURL.

The destination should not yet exist. The destination URL must end in a filename; there is no implicit adoption of the source filename.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the link operation is successful. If the operation is not successful, but the delegate returns YES from the fileManager:shouldProceedAfterError:linkingItemAtURL:toURL: message, linkItemAtURL:toURL:error: also returns YES. Otherwise this method returns NO.

Discussion

If srcURL identifies a file, this method hard-links the file specified in dstURL to it. If srcURL is a symbolic link, this method copies it to dstURL instead of creating a hard link. Symbolic links in srcURL are not traversed.

Amongst other reasons (such as the disk being full, permissions problems, and so on), this method will fail if:

NSFileManager sends your delegate fileManager:shouldLinkItemAtURL:toURL: when it begins a hard-link operation. If the delegate returns YES, NSFileManager attempts to hard-link the item. If the delegate returns NO, the linkItemAtURL:toURL:error: function does not hard-link the item.

NSFileManager sends your delegate fileManager:shouldProceedAfterError:linkingItemAtURL:toURL: when it encounters any error in processing. If the delegate returns YES, then NSFileManager proceeds as if no error had occurred. If it returns NO, the linkItemAtURL:toURL:error: function terminates and passes the error back in the error parameter.

Availability
  • Available in Mac OS X v10.6 and later.
See Also
Declared In
NSFileManager.h

mountedVolumeURLsIncludingResourceValuesForKeys:options:

Returns the mounted volumes available on the computer.

- (NSArray *)mountedVolumeURLsIncludingResourceValuesForKeys:(NSArray *)propertyKeys options:(NSVolumeEnumerationOptions)options

Parameters
propertyKeys

On input, an array of property keys for which the corresponding resource values should be pre-fetched. Specify NULL for this array if you do not want any resource values. The property keys that can be requested are listed in Common File System Resource Keys.

options

Option flags for the enumeration. See “Mounted Volume Enumeration Options.”

Return Value

An array of NSURL objects identifying the mounted volumes.

Discussion

This call may block if I/O is required to determine values for the requested propertyKeys.

Availability
  • Available in Mac OS X v10.6 and later.
Declared In
NSFileManager.h

moveItemAtPath:toPath:error:

Moves the directory or file specified by a given path to a different location in the file system identified by another path.

- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error

Parameters
srcPath

The path of a file or directory to move. srcPath must exist.

dstPath

The path to which the file or directory at srcPath is to be moved. destination must not yet exist. The destination path must end in a directory name or filename; there is no implicit adoption of the source name.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the move operation is successful. If the operation is not successful, but the delegate returns YES from the fileManager:shouldProceedAfterError:movingItemAtPath:toPath: message, moveItemAtPath:toPath:error: also returns YES. Otherwise this method returns NO.

Discussion

If the source path and the destination path are not on the same device, NSFileManager performs a copy to the destination path and removes the original. If the copy does not succeed, this method returns an error and NSFileManager removes the incomplete copy, leaving the original in place.

NSFileManager sends your delegate fileManager:shouldMoveItemAtPath:toPath: when it begins a move operation. If the delegate returns YES, NSFileManager attempts to move the item. If the delegate returns NO, the moveItemAtPath:toPath:error: function does not move the item.

NSFileManager sends your delegate fileManager:shouldProceedAfterError:movingItemAtPath:toPath: when it encounters any error in processing. If the delegate returns YES, then NSFileManager proceeds as if no error had occurred. If it returns NO, the moveItemAtPath:toPath:error: function terminates and passes the error back in the error parameter.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Declared In
NSFileManager.h

moveItemAtURL:toURL:error:

Moves the directory or file specified by a given URL to a different location in the file system identified by another URL.

- (BOOL)moveItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error

Parameters
srcURL

The URL of a file or directory to move. srcURL must exist.

dstURL

The URL to which the file or directory at srcURL is to be moved. destination must not yet exist. The destination URL must end in a directory name or filename; there is no implicit adoption of the source name.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the move operation is successful. If the operation is not successful, but the delegate returns YES from the fileManager:shouldProceedAfterError:movingItemAtURL:toURL: message, moveItemAtURL:toURL:error: also returns YES. Otherwise this method returns NO.

Discussion

If the source path and the destination path are not on the same device, NSFileManager performs a copy to the destination path and removes the original. If the copy does not succeed, this method returns an error and NSFileManager removes the incomplete copy, leaving the original in place.

NSFileManager sends your delegate fileManager:shouldMoveItemAtURL:toURL: when it begins a move operation. If the delegate returns YES, NSFileManager attempts to move the item. If the delegate returns NO, the moveItemAtURL:toURL:error: function does not move the item.

NSFileManager sends your delegate fileManager:shouldProceedAfterError:movingItemAtURL:toURL: when it encounters any error in processing. If the delegate returns YES, then NSFileManager proceeds as if no error had occurred. If it returns NO, the moveItemAtURL:toURL:error: function terminates and passes the error back in the error parameter.

Availability
  • Available in Mac OS X v10.6 and later.
See Also
Declared In
NSFileManager.h

removeItemAtPath:error:

Deletes the file, link, or directory (including, recursively, all subdirectories, files, and links in the directory) identified by a given path.

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

Parameters
path

The path of a file, link, or directory to delete. The value must not be "." or "..".

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the removal operation is successful. If the operation is not successful, but the delegate returns YES from the fileManager:shouldProceedAfterError:removingItemAtPath: message, removeItemAtPath:error: also returns YES. Otherwise this method returns NO.

Discussion

Since the removal of directory contents is so thorough and final, be careful when using this method. If you specify "." or ".." for path an NSInvalidArgumentException exception is raised. This method does not traverse symbolic links.

NSFileManager sends your delegate fileManager:shouldRemoveItemAtPath: when it begins a delete operation. If the delegate returns YES, NSFileManager attempts to delete the item. If the delegate returns NO, the removeItemAtPath:error: function does not delete the item and, if the item is a directory, no children of that item are deleted either.

NSFileManager sends your delegate fileManager:shouldProceedAfterError:removingItemAtPath: when it encounters any error in processing. If the delegate returns YES, then NSFileManager proceeds as if no error had occurred. If it returns NO, the removeItemAtPath:error: function terminates and passes the error back in the error parameter.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

removeItemAtURL:error:

Deletes the file, link, or directory (including, recursively, all subdirectories, files, and links in the directory) identified by a given URL.

- (BOOL)removeItemAtURL:(NSURL *)URL error:(NSError **)error

Parameters
URL

The URL of a file, link, or directory to delete. The value must not be "." or "..".

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if the removal operation is successful. If the operation is not successful, but the delegate returns YES from the fileManager:shouldProceedAfterError:removingItemAtURL: message, removeItemAtURL:error: also returns YES. Otherwise this method returns NO.

Discussion

Since the removal of directory contents is so thorough and final, be careful when using this method. If you specify "." or ".." for URL an NSInvalidArgumentException exception is raised. This method does not traverse symbolic links.

NSFileManager sends your delegate fileManager:shouldRemoveItemAtURL: when it begins a delete operation. If the delegate returns YES, NSFileManager attempts to delete the item. If the delegate returns NO, the removeItemAtURL:error: function does not delete the item and, if the item is a directory, no children of that item are deleted either.

NSFileManager sends your delegate fileManager:shouldProceedAfterError:removingItemAtURL: when it encounters any error in processing. If the delegate returns YES, then NSFileManager proceeds as if no error had occurred. If it returns NO, the removeItemAtURL:error: function terminates and passes the error back in the error parameter.

Availability
  • Available in Mac OS X v10.6 and later.
See Also
Declared In
NSFileManager.h

replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:

Replaces the contents specified by the first URL with the contents of the second URL in a manner that insures no data loss occurs.

- (BOOL)replaceItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL backupItemName:(NSString *)backupItemName options:(NSFileManagerItemReplacementOptions)options resultingItemURL:(NSURL **)resultingURL error:(NSError **)error

Parameters
originalItemURL

The item being replaced.

newItemURL

The item which will replace the originalItemURL. This item should be placed in a temporary directory as provided by the OS, or in a uniquely named directory placed in the same directory as the original item if the temporary directory is not available.

backupItemName

Optional. If provided, this name will be used to create a backup of the original item.

The backup is placed in the same directory as the original item. If an error occurs during the creation of the backup item, the operation will fail. If there is already an item with the same name as the backup item, that item will be removed.

The backup item will be removed in the event of success unless the NSFileManagerItemReplacementWithoutDeletingBackupItem option is provided in options.

options

Specifies the options used in the replacement. Passing 0 provides the default behavior which uses only the metadata from the new item. The values in “NSFileManagerItemReplacementOptions” are also valid and can be combined using the C-bitwise OR operator. Typically 0 is passed.

resultingURL

This URL will be set to the URL which points at the new item. resultingURL may be the same as originalItemURL if the replacement could be made without having to create a new filesystem object. resultingURL may be different than originalItemURL if the replacement could not be made without having to create a new object (e.g. going from an rtf document to an rtfd requires the creation of a new item - in this case, resultingURL would locate the newly-created rtfd).

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

Returns YES if the replacement was successful, otherwise NO.

Discussion

By default, the creation date, permissions, Finder label and color, and Spotlight comments of the original item will be preserved on the resulting item.

If an error occurs in replacing a filesystem item and the original item has been left in neither the original location nor the temporary location, the NSError returned will contain a user info dictionary with the NSFileOriginalItemLocationKey key and its value will be an NSURL instance which locates the item. The error code is one of the various NSFile* errors already present in NSError Codes.

Availability
  • Available in Mac OS X v10.6 and later.
Declared In
NSFileManager.h

setAttributes:ofItemAtPath:error:

Sets the attributes of a given file or directory.

- (BOOL)setAttributes:(NSDictionary *)attributes ofItemAtPath:(NSString *)path error:(NSError **)error

Parameters
attributes

A dictionary containing as keys the attributes to set for path and as values the corresponding value for the attribute. You can set the following attributes: NSFileBusy, NSFileCreationDate, NSFileExtensionHidden, NSFileGroupOwnerAccountID, NSFileGroupOwnerAccountName, NSFileHFSCreatorCode, NSFileHFSTypeCode, NSFileImmutable, NSFileModificationDate, NSFileOwnerAccountID, NSFileOwnerAccountName, NSFilePosixPermissions. You can change single attributes or any combination of attributes; you need not specify keys for all attributes.

path

The path of a file or directory.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

YES if all changes succeed. If any change fails, returns NO, but it is undefined whether any changes actually occurred.

Discussion

As in the POSIX standard, the application either must own the file or directory or must be running as superuser for attribute changes to take effect. The method attempts to make all changes specified in attributes and ignores any rejection of an attempted modification. If the last component of the path is a symbolic link it is traversed.

The NSFilePosixPermissions value must be initialized with the code representing the POSIX file-permissions bit pattern. NSFileHFSCreatorCode and NSFileHFSTypeCode will only be heeded when path specifies a file.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Declared In
NSFileManager.h

setDelegate:

Sets the delegate for the receiver.

- (void)setDelegate:(id)delegate

Parameters
delegate

The delegate for the receiver.

Availability
  • Available in Mac OS X v10.5 and later.
Declared In
NSFileManager.h

stringWithFileSystemRepresentation:length:

Returns an NSString object converted from the C-string representation of a pathname in the current file system.

- (NSString *)stringWithFileSystemRepresentation:(const char *)string length:(NSUInteger)len

Parameters
string

A C string representation of a pathname.

len

The number of characters in string.

Return Value

An NSString object converted from the C-string representation string with length len of a pathname in the current file system.

Discussion

Use this method if your code receives paths as C strings from system routines.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Related Sample Code
Declared In
NSFileManager.h

subpathsAtPath:

Returns an array that contains (as NSString objects) the contents of the directory identified by a given path.

- (NSArray *)subpathsAtPath:(NSString *)path

Parameters
path

The path of the directory to list.

Return Value

An array that contains (as NSString objects) the contents of the directory identified by path. If path is a symbolic link, subpathsAtPath: traverses the link. Returns nil if it cannot get the device of the linked-to file.

Discussion

This list of directory contents goes very deep and hence is very useful for large file-system subtrees. The method skips “.” and “..”.

This method reveals every element of the subtree at path, including the contents of file packages (such as applications, nib files, and RTFD files). This code fragment gets the contents of /System/Library/Fonts after verifying that the directory exists:

BOOL isDir=NO;
NSArray *subpaths;
NSString *fontPath = @"/System/Library/Fonts";
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir)
    subpaths = [fileManager subpathsAtPath:fontPath];
Special Considerations

On Mac OS X v10.5 and later, use subpathsOfDirectoryAtPath:error: instead.

Availability
  • Available in Mac OS X v10.0 and later.
See Also
Declared In
NSFileManager.h

subpathsOfDirectoryAtPath:error:

Returns an array that contains the filenames of the items in the directory specified by a given path and all its subdirectories recursively.

- (NSArray *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error

Parameters
path

The path of the directory to list.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

An array that contains NSString objects representing the filenames of the items in the directory specified by path and all its subdirectories recursively. If path is a symbolic link, subpathsOfDirectoryAtPath:error: traverses the link. Returns nil if it cannot get the device of the linked-to file.

Discussion

This list of directory contents goes very deep and hence is very useful for large file-system subtrees. The method skips “.” and “..”.

Availability
  • Available in Mac OS X v10.5 and later.
See Also
Declared In
NSFileManager.h

URLForDirectory:inDomain:appropriateForURL:create:error:

Locates and optionally creates the specified common directory in a domain.

- (NSURL *)URLForDirectory:(NSSearchPathDirectory)directory inDomain:(NSSearchPathDomainMask)domain appropriateForURL:(NSURL *)url create:(BOOL)shouldCreate error:(NSError **)error

Parameters
directory

The search path directory. The supported values are described in NSSearchPathDirectory.

domain

The domain specifies where the search should occur. The constants are specified by NSSearchPathDomainMask. Note: You may not pass the NSAllDomainsMask.

url

If not NULL, and directory is NSItemReplacementDirectory the appropriate temporary directory will be located. If the URL is located on another machine, the temporary directory will be on the other machine. If the URL is local, the temporary directory will be local.

shouldCreate

YES if the directory should be created if it doesn’t exist, otherwise NO.

error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value

Returns an NSURL specifying the directory, or nil if an error was encountered.

Discussion

Passing a directory and domain pair that makes no sense (for example NSDesktopDirectory and NSNetworkDomainMask) will raise an exception.

Availability
  • Available in Mac OS X v10.6 and later.
Declared In
NSFileManager.h

URLsForDirectory:inDomains:

Returns an array of URLs for the specified common directory in the requested domains.

- (NSArray *)URLsForDirectory:(NSSearchPathDirectory)directory inDomains:(NSSearchPathDomainMask)domainMask

Parameters
directory

The search path directory. The supported values are described in NSSearchPathDirectory.

domainMask

The domain specifies where the search should occur. The constants are specified by NSSearchPathDomainMask.

Return Value

An array of URLs containing the directories, in the order in which they should be searched.

Discussion

This method is intended to locate known and common directories in the system. For example, setting the directory to NSApplicationDirectory, will return the Applications directories in the requested domain. There are a number of common directories available in the NSSearchPathDirectory, including: NSDesktopDirectory, NSApplicationSupportDirectory, and many more.

Availability
  • Available in Mac OS X v10.6 and later.
Declared In
NSFileManager.h

Delegate Methods

fileManager:shouldCopyItemAtPath:toPath:

An NSFileManager object sends this message immediately before attempting to copy to a given path.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath

Parameters
fileManager

The NSFileManager object that sent this message.

srcPath

The path or a file or directory that fileManager is about to attempt to copy.

dstPath

The path or a file or directory to which fileManager is about to attempt to copy.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

Returning NO from this method causes NSFileManager to stop copying the item. If the item skipped is a directory, no children of that directory are copied, nor is the delegate notified of those children.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldCopyItemAtURL:toURL:

An NSFileManager object sends this message immediately before attempting to copy to a given URL.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL

Parameters
fileManager

The NSFileManager object that sent this message.

srcURL

The URL or a file or directory that fileManager is about to attempt to copy.

dstURL

The URL or a file or directory to which fileManager is about to attempt to copy.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

Returning NO from this method causes NSFileManager to stop copying the item. If the item skipped is a directory, no children of that directory are copied, nor is the delegate notified of those children.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldLinkItemAtPath:toPath:

An NSFileManager object sends this message immediately before attempting to link to a given path.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldLinkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath

Parameters
fileManager

The NSFileManager object that sent this message.

srcPath

The path or a file or directory that fileManager is about to attempt to link.

dstPath

The path or a file or directory to which fileManager is about to attempt to link.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

Returning NO from this method causes NSFileManager to stop creating the link.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldLinkItemAtURL:toURL:

An NSFileManager object sends this message immediately before attempting to link to a given URL.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldLinkItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL

Parameters
fileManager

The NSFileManager object that sent this message.

srcURL

The URL or a file or directory that fileManager is about to attempt to link.

dstURL

The URL or a file or directory to which fileManager is about to attempt to link.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

Returning NO from this method causes NSFileManager to stop creating the link.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldMoveItemAtPath:toPath:

An NSFileManager object sends this message immediately before attempting to move to a given path.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldMoveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath

Parameters
fileManager

The NSFileManager object that sent this message.

srcPath

The path of a file or directory that fileManager is about to attempt to move.

dstPath

The path of a file or directory to which fileManager is about to attempt to move.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

Returning NO from this method causes NSFileManager to stop moving the item. In a move operation, if the source path and the destination path are not on the same device, a copy is performed to the destination path and the original is removed. If the copy does not succeed, NSFileManager returns an error and removes the incomplete copy, leaving the original in place.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldMoveItemAtURL:toURL:

An NSFileManager object sends this message immediately before attempting to move to a given URL.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldMoveItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL

Parameters
fileManager

The NSFileManager object that sent this message.

srcURL

The URL of a file or directory that fileManager is about to attempt to move.

dstURL

The URL of a file or directory to which fileManager is about to attempt to move.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

Returning NO from this method causes NSFileManager to stop moving the item. In a move operation, if the source URL and the destination URL are not on the same device, a copy is performed to the destination URL and the original is removed. If the copy does not succeed, NSFileManager returns an error and removes the incomplete copy, leaving the original in place.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldProceedAfterError:copyingItemAtPath:toPath:

An NSFileManager object sends this message if an error occurs during an attempt to copy to a given path.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath

Parameters
fileManager

The NSFileManager object that sent this message.

error

The error that occurred during the attempt to copy.

srcPath

The path or a file or directory that fileManager is attempting to copy.

dstPath

The path or a file or directory to which fileManager is attempting to copy.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

If this method returns YES, the NSFileManager instance continues as if the error had not occurred. If this method returns NO, the NSFileManager instance stops copying, and copyItemAtPath:toPath:error: returns NO and provides the error in its error argument.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldProceedAfterError:copyingItemAtURL:toURL:

An NSFileManager object sends this message if an error occurs during an attempt to copy to a given URL.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL

Parameters
fileManager

The NSFileManager object that sent this message.

error

The error that occurred during the attempt to copy.

srcURL

The URL or a file or directory that fileManager is attempting to copy.

dstURL

The URL or a file or directory to which fileManager is attempting to copy.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

If this method returns YES, the NSFileManager instance continues as if the error had not occurred. If this method returns NO, the NSFileManager instance stops copying, and copyItemAtURL:toURL:error: returns NO and provides the error in its error argument.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldProceedAfterError:linkingItemAtPath:toPath:

An NSFileManager object sends this message if an error occurs during an attempt to hard-link to a given path.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error linkingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath

Parameters
fileManager

The NSFileManager object that sent this message.

error

The error that occurred during the attempt to link.

srcPath

The path or a file or directory that fileManager is attempting to link.

dstPath

The path or a file or directory to which fileManager is attempting to link.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

If this method returns YES, the NSFileManager instance continues as if the error had not occurred. If this method returns NO, the NSFileManager instance stops linking the item, and linkItemAtPath:toPath:error: returns NO and provides the error in its error argument.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldProceedAfterError:linkingItemAtURL:toURL:

An NSFileManager object sends this message if an error occurs during an attempt to hard-link to a given URL.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error linkingItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL

Parameters
fileManager

The NSFileManager object that sent this message.

error

The error that occurred during the attempt to link.

srcURL

The URL or a file or directory that fileManager is attempting to link.

dstURL

The URL or a file or directory to which fileManager is attempting to link.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

If this method returns YES, the NSFileManager instance continues as if the error had not occurred. If this method returns NO, the NSFileManager instance stops linking the item, and linkItemAtURL:toURL:error: returns NO and provides the error in its error argument.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldProceedAfterError:movingItemAtPath:toPath:

An NSFileManager object sends this message if an error occurs during an attempt to move to a given path.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error movingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath

Parameters
fileManager

The NSFileManager object that sent this message.

error

The error that occurred during the attempt to move.

srcPath

The path or a file or directory that fileManager is attempting to move.

dstPath

The path or a file or directory to which fileManager is attempting to move.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

If this method returns YES, the NSFileManager instance continues as if the error had not occurred. If this method returns NO, the NSFileManager instance stops moving the item, and moveItemAtPath:toPath:error: returns NO and provides the error in its error argument.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldProceedAfterError:movingItemAtURL:toURL:

An NSFileManager object sends this message if an error occurs during an attempt to move to a given URL.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error movingItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL

Parameters
fileManager

The NSFileManager object that sent this message.

error

The error that occurred during the attempt to move.

srcURL

The URL or a file or directory that fileManager is attempting to move.

dstURL

The URL or a file or directory to which fileManager is attempting to move.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

If this method returns YES, the NSFileManager instance continues as if the error had not occurred. If this method returns NO, the NSFileManager instance stops moving the item, and moveItemAtURL:toURL:error: returns NO and provides the error in its error argument.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldProceedAfterError:removingItemAtPath:

An NSFileManager object sends this message if an error occurs during an attempt to delete a given path.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error removingItemAtPath:(NSString *)path

Parameters
fileManager

The NSFileManager object that sent this message.

error

The error that occurred during the attempt to copy.

path

The path or a file or directory that fileManager is attempting to delete.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

If this method returns YES, the NSFileManager instance continues as if the error had not occurred. If this method returns NO, the NSFileManager instance stops deleting the item, and removeItemAtPath:error: returns NO and provides the error in its error argument.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldProceedAfterError:removingItemAtURL:

An NSFileManager object sends this message if an error occurs during an attempt to delete a given URL.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error removingItemAtURL:(NSURL *)URL

Parameters
fileManager

The NSFileManager object that sent this message.

error

The error that occurred during the attempt to copy.

URL

The URL or a file or directory that fileManager is attempting to delete.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

If this method returns YES, the NSFileManager instance continues as if the error had not occurred. If this method returns NO, the NSFileManager instance stops deleting the item, and removeItemAtURL:error: returns NO and provides the error in its error argument.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldRemoveItemAtPath:

An NSFileManager object sends this message immediately before attempting to delete an item at a given path.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldRemoveItemAtPath:(NSString *)path

Parameters
fileManager

The NSFileManager object that sent this message.

path

The path or a file or directory that fileManager is about to attempt to delete.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

Returning NO from this method causes NSFileManager to stop deleting the item. If the item is a directory, no children of that item are deleted either.

Availability
See Also
Declared In
NSFileManager.h

fileManager:shouldRemoveItemAtURL:

An NSFileManager object sends this message immediately before attempting to delete an item at a given URL.

- (BOOL)fileManager:(NSFileManager *)fileManager shouldRemoveItemAtURL:(NSURL *)URL

Parameters
fileManager

The NSFileManager object that sent this message.

URL

The URL or a file or directory that fileManager is about to attempt to delete.

Return Value

YES if the operation should proceed, otherwise NO.

Discussion

Returning NO from this method causes NSFileManager to stop deleting the item. If the item is a directory, no children of that item are deleted either.

Availability
See Also
Declared In
NSFileManager.h

Constants

Mounted Volume Enumeration Options

Options for enumerating mounted volumes with the mountedVolumeURLsIncludingResourceValuesForKeys:options: method.

enum {
   NSVolumeEnumerationSkipHiddenVolumes        = 1L << 1,
   NSVolumeEnumerationProduceFileReferenceURLs = 1L << 2
};
typedef NSUInteger NSVolumeEnumerationOptions;
Constants
NSVolumeEnumerationSkipHiddenVolumes

The enumeration skips hidden volumes.

Available in Mac OS X v10.6 and later.

Declared in NSFileManager.h.

NSVolumeEnumerationProduceFileReferenceURLs

The enumeration produces file reference URLs rather than path-based URLs.

Available in Mac OS X v10.6 and later.

Declared in NSFileManager.h.

Directory Enumeration Options

Options for enumerating the contents of directories with the contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: method.

enum {
   NSDirectoryEnumerationSkipsSubdirectoryDescendants = 1L << 0,
   NSDirectoryEnumerationSkipsPackageDescendants      = 1L << 1,
   NSDirectoryEnumerationSkipsHiddenFiles             = 1L << 2
};
typedef NSUInteger NSDirectoryEnumerationOptions;
Constants
NSDirectoryEnumerationSkipsSubdirectoryDescendants

Perform a shallow enumeration; do not descend into directories.

Available in Mac OS X v10.6 and later.

Declared in NSFileManager.h.

NSDirectoryEnumerationSkipsPackageDescendants

Do not descend into packages.

Available in Mac OS X v10.6 and later.

Declared in NSFileManager.h.

NSDirectoryEnumerationSkipsHiddenFiles

Do not enumerate hidden files.

Available in Mac OS X v10.6 and later.

Declared in NSFileManager.h.

NSFileManagerItemReplacementOptions

The constants specify the replacement behavior in NSFileManagerItemReplacementWithoutDeletingBackupItem.

enum {
   NSFileManagerItemReplacementUsingNewMetadataOnly = 1UL << 0,
   NSFileManagerItemReplacementWithoutDeletingBackupItem = 1UL << 1
};
typedef NSUInteger NSFileManagerItemReplacementOptions;
Constants
NSFileManagerItemReplacementUsingNewMetadataOnly

Causes NSFileManagerItemReplacementWithoutDeletingBackupItem to use metadata from the new item only and not to attempt to preserve metadata from the original item.

Available in Mac OS X v10.6 and later.

Declared in NSFileManager.h.

NSFileManagerItemReplacementWithoutDeletingBackupItem

Causes NSFileManagerItemReplacementWithoutDeletingBackupItem to leave the backup item in place after a successful replacement. The default behavior is to remove the item.

Available in Mac OS X v10.6 and later.

Declared in NSFileManager.h.

File Attribute Keys

These keys access file attribute values contained in NSDictionary objects used by setAttributes:ofItemAtPath:error:, attributesOfItemAtPath:error:, createDirectoryAtPath:withIntermediateDirectories:attributes:error:, and createFileAtPath:contents:attributes:.

NSString * const NSFileType;
NSString * const NSFileSize;
NSString * const NSFileModificationDate;
NSString * const NSFileReferenceCount;
NSString * const NSFileDeviceIdentifier;
NSString * const NSFileOwnerAccountName;
NSString * const NSFileGroupOwnerAccountName;
NSString * const NSFilePosixPermissions;
NSString * const NSFileSystemNumber;
NSString * const NSFileSystemFileNumber;
NSString * const NSFileExtensionHidden;
NSString * const NSFileHFSCreatorCode;
NSString * const NSFileHFSTypeCode;
NSString * const NSFileImmutable;
NSString * const NSFileAppendOnly;
NSString * const NSFileCreationDate;
NSString * const NSFileOwnerAccountID;
NSString * const NSFileGroupOwnerAccountID;
NSString * const NSFileBusy;
Constants
NSFileAppendOnly

The key in a file attribute dictionary whose value indicates whether the file is read-only.

The corresponding value is an NSNumber object containing a Boolean value.

Available in Mac OS X v10.2 and later.

Declared in NSFileManager.h.

NSFileBusy

The key in a file attribute dictionary whose value indicates whether the file is busy.

The corresponding value is an NSNumber object containing a Boolean value.

Available in Mac OS X v10.4 and later.

Declared in NSFileManager.h.

NSFileCreationDate

The key in a file attribute dictionary whose value indicates the file's creation date.

The corresponding value is an NSDate object.

Available in Mac OS X v10.2 and later.

Declared in NSFileManager.h.

NSFileOwnerAccountName

The key in a file attribute dictionary whose value indicates the name of the file's owner.

The corresponding value is an NSString object.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileGroupOwnerAccountName

The key in a file attribute dictionary whose value indicates the group name of the file's owner.

The corresponding value is an NSString object.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileDeviceIdentifier

The key in a file attribute dictionary whose value indicates the identifier for the device on which the file resides.

The corresponding value is an NSNumber object containing an unsigned long.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileExtensionHidden

The key in a file attribute dictionary whose value indicates whether the file's extension is hidden.

The corresponding value is an NSNumber object containing a Boolean value.

Available in Mac OS X v10.1 and later.

Declared in NSFileManager.h.

NSFileGroupOwnerAccountID

The key in a file attribute dictionary whose value indicates the file's group ID.

The corresponding value is an NSNumber object containing an unsigned long.

Available in Mac OS X v10.2 and later.

Declared in NSFileManager.h.

NSFileHFSCreatorCode

The key in a file attribute dictionary whose value indicates the file's HFS creator code.

The corresponding value is an NSNumber object containing an unsigned long. See HFS File Types for possible values.

Available in Mac OS X v10.1 and later.

Declared in NSFileManager.h.

NSFileHFSTypeCode

The key in a file attribute dictionary whose value indicates the file's HFS type code.

The corresponding value is an NSNumber object containing an unsigned long. See HFS File Types for possible values.

Available in Mac OS X v10.1 and later.

Declared in NSFileManager.h.

NSFileImmutable

The key in a file attribute dictionary whose value indicates whether the file is mutable.

The corresponding value is an NSNumber object containing a Boolean value.

Available in Mac OS X v10.2 and later.

Declared in NSFileManager.h.

NSFileModificationDate

The key in a file attribute dictionary whose value indicates the file's last modified date.

The corresponding value is an NSDate object.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileOwnerAccountID

The key in a file attribute dictionary whose value indicates the file's owner's account ID.

The corresponding value is an NSNumber object containing an unsigned long.

Available in Mac OS X v10.2 and later.

Declared in NSFileManager.h.

NSFilePosixPermissions

The key in a file attribute dictionary whose value indicates the file's Posix permissions.

The corresponding value is an NSNumber object containing an unsigned long.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileReferenceCount

The key in a file attribute dictionary whose value indicates the file's reference count.

The corresponding value is an NSNumber object containing an unsigned long.

The number specifies the number of hard links to a file.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileSize

The key in a file attribute dictionary whose value indicates the file's size in bytes.

The corresponding value is an NSNumber object containing an unsigned long long.

Important: If the file has a resource fork, the returned value does not include the size of the resource fork.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileSystemFileNumber

The key in a file attribute dictionary whose value indicates the file's filesystem file number.

The corresponding value is an NSNumber object containing an unsigned long. The value corresponds to the value of st_ino, as returned by stat(2).

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileType

The key in a file attribute dictionary whose value indicates the file's type.

The corresponding value is an NSString object (see “NSFileType Attribute Values” for possible values).

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

Discussion

NSFileDeviceIdentifier is used to access the identifier of a remote device.

Declared In
NSFileManager.h

NSFileType Attribute Values

These strings are the possible values for the NSFileType attribute key contained in the NSDictionary object returned by attributesOfItemAtPath:error:.

NSString * const NSFileTypeDirectory;
NSString * const NSFileTypeRegular;
NSString * const NSFileTypeSymbolicLink;
NSString * const NSFileTypeSocket;
NSString * const NSFileTypeCharacterSpecial;
NSString * const NSFileTypeBlockSpecial;
NSString * const NSFileTypeUnknown;
Constants
NSFileTypeDirectory

Directory

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileTypeRegular

Regular file

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileTypeSymbolicLink

Symbolic link

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileTypeSocket

Socket

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileTypeCharacterSpecial

Character special file

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileTypeBlockSpecial

Block special file

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileTypeUnknown

Unknown

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

File-System Attribute Keys

Keys to access the file attribute values contained in the NSDictionary object returned from NSFileManager’s attributesOfFileSystemForPath:error: method.

extern NSString *NSFileSystemSize;
extern NSString *NSFileSystemFreeSize;
extern NSString *NSFileSystemNodes;
extern NSString *NSFileSystemFreeNodes;
extern NSString *NSFileSystemNumber;
Constants
NSFileSystemSize

The key in a file system attribute dictionary whose value indicates the size of the file system.

The corresponding value is an NSNumber object that specifies the size of the file system in bytes. The value is determined by statfs().

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileSystemFreeSize

The key in a file system attribute dictionary whose value indicates the amount of free space on the file system.

The corresponding value is an NSNumber object that specifies the amount of free space on the file system in bytes. The value is determined by statfs().

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileSystemNodes

The key in a file system attribute dictionary whose value indicates the number of nodes in the file system.

The corresponding value is an NSNumber object that specifies the number of nodes in the file system.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileSystemFreeNodes

The key in a file system attribute dictionary dictionary whose value indicates the number of free nodes in the file system.

The corresponding value is an NSNumber object that specifies the number of free nodes in the file system.

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

NSFileSystemNumber

The key in a file system attribute dictionary dictionary whose value indicates the filesystem number of the file system.

The corresponding value is an NSNumber object that specifies the filesystem number of the file system. The value corresponds to the value of st_dev, as returned by stat(2).

Available in Mac OS X v10.0 and later.

Declared in NSFileManager.h.

Resource Fork Support

Specifies the version of the Foundation framework in which NSFileManager first supported resource forks.

#define NSFoundationVersionWithFileManagerResourceForkSupport 412
Constants
NSFoundationVersionWithFileManagerResourceForkSupport

The version of the Foundation framework in which NSFileManager first supported resource forks.

Available in Mac OS X v10.1 and later.

Declared in NSFileManager.h.

Declared In
NSFileManager.h


Last updated: 2009-11-17

Did this document help you? Yes It's good, but... Not helpful...