NSFileManager Class Reference
| Inherits from | |
| Conforms to | |
| Framework | /System/Library/Frameworks/Foundation.framework |
| Availability | Available in OS X v10.0 and later. |
| Companion guide | |
| Declared in | NSFileManager.h |
Overview
The NSFileManager class enables you to perform many generic file-system operations and insulates an app from the underlying file system. Most file operations can be performed using the shared file manager object. In iOS and in OS X v10.5 and later, you can also create a unique instance of NSFileManager in cases where you want to use a delegate object in conjunction with the file manager.
In Cocoa apps, a file manager object is usually your first interaction with the file system. You use this object to locate, create, copy, and move files and directories. You also use this object to get information about files and directories, such as its size, modification date, and BSD permissions. You can also use a file manager object to change the values of many file and directory attributes.
The NSFileManager class supports both the NSURL and NSString classes as ways to specify the location of a file or directory. The use of the NSURL class is generally preferred for specifying file-system items because they can convert path information to a more efficient representation internally. You can also obtain a bookmark from an NSURL object, which is similar to an alias and offers a more sure way of locating the file or directory later.
If you are moving, copying, linking, or removing files or directories, you can use a delegate in conjunction with a file manager object to manage those operations. The delegate’s role is to affirm the operation and to decide whether to proceed when errors occur. In OS X v10.7 and later, the delegate must conform to the NSFileManagerDelegate protocol.
In iOS 5.0 and later and in OS X v10.7 and later, NSFileManager includes methods for managing items stored in the cloud. Files and directories tagged for cloud storage are synced to iCloud so that they can be made available to the user’s iOS devices and Macintosh computers. Changes to an item in one location are propagated to all other locations to ensure the items stay in sync.
Threading Considerations
The methods of the shared NSFileManager object can be called from multiple threads safely. However, if you use a delegate to receive notifications about the status of move, copy, remove, and link operations, you should create a unique instance of the file manager object, assign your delegate to that object, and use that file manager to initiate your operations.
Tasks
Creating a File Manager
Locating System Directories
Locating Application Group Container Directories
Discovering Directory Contents
-
– contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: -
– contentsOfDirectoryAtPath:error: -
– enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: -
– enumeratorAtPath: -
– mountedVolumeURLsIncludingResourceValuesForKeys:options: -
– subpathsOfDirectoryAtPath:error: -
– subpathsAtPath:
Creating and Deleting Items
-
– createDirectoryAtURL:withIntermediateDirectories:attributes:error: -
– createDirectoryAtPath:withIntermediateDirectories:attributes:error: -
– createFileAtPath:contents:attributes: -
– removeItemAtURL:error: -
– removeItemAtPath:error: -
– replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: -
– trashItemAtURL:resultingItemURL:error:
Moving and Copying Items
-
– copyItemAtURL:toURL:error: -
– copyItemAtPath:toPath:error: -
– moveItemAtURL:toURL:error: -
– moveItemAtPath:toPath:error:
Managing ICloud-Based Items
-
– ubiquityIdentityToken -
– URLForUbiquityContainerIdentifier: -
– isUbiquitousItemAtURL: -
– setUbiquitous:itemAtURL:destinationURL:error: -
– startDownloadingUbiquitousItemAtURL:error: -
– evictUbiquitousItemAtURL:error: -
– URLForPublishingUbiquitousItemAtURL:expirationDate:error:
Creating Symbolic and Hard Links
-
– createSymbolicLinkAtURL:withDestinationURL:error: -
– createSymbolicLinkAtPath:withDestinationPath:error: -
– linkItemAtURL:toURL:error: -
– linkItemAtPath:toPath:error: -
– destinationOfSymbolicLinkAtPath:error:
Determining Access to Files
-
– fileExistsAtPath: -
– fileExistsAtPath:isDirectory: -
– isReadableFileAtPath: -
– isWritableFileAtPath: -
– isExecutableFileAtPath: -
– isDeletableFileAtPath:
Getting and Setting Attributes
-
– componentsToDisplayForPath: -
– displayNameAtPath: -
– attributesOfItemAtPath:error: -
– attributesOfFileSystemForPath:error: -
– setAttributes:ofItemAtPath:error:
Getting and Comparing File Contents
Converting File Paths to Strings
Managing the Delegate
Managing the Current Directory
Deprecated Methods
-
– changeFileAttributes:atPath:Deprecated in OS X v10.5 -
– copyPath:toPath:handler:Deprecated in OS X v10.5 -
– createDirectoryAtPath:attributes:Deprecated in OS X v10.5 -
– createSymbolicLinkAtPath:pathContent:Deprecated in OS X v10.5 -
– directoryContentsAtPath:Deprecated in OS X v10.5 -
– fileAttributesAtPath:traverseLink:Deprecated in OS X v10.5 -
– fileSystemAttributesAtPath:Deprecated in OS X v10.5 -
– linkPath:toPath:handler:Deprecated in OS X v10.5 -
– movePath:toPath:handler:Deprecated in OS X v10.5 -
– pathContentOfSymbolicLinkAtPath:Deprecated in OS X v10.5 -
– removeFileAtPath:handler:Deprecated in OS X v10.5 -
– fileManager:shouldProceedAfterError:delegate method Deprecated in OS X v10.5 -
– fileManager:willProcessPath:delegate method Deprecated in OS X v10.5
Class Methods
defaultManager
Returns the shared file manager object for the process.
Return Value
The default NSFileManager object for the file system.
Discussion
This method always returns the same file manager object. If you plan to use a delegate with the file manager to receive notifications about the completion of file-based operations, you should create a new instance of NSFileManager (using the init method) rather than using the shared object.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hInstance Methods
attributesOfFileSystemForPath:error:
Returns a dictionary that describes the attributes of the mounted file system on which a given path resides.
Parameters
- path
Any pathname within the mounted file system.
- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the 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 OS X v10.5 and later.
Declared In
NSFileManager.hattributesOfItemAtPath:error:
Returns the attributes of the item at a given path.
Parameters
- path
The path of a file or directory.
- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
An NSDictionary object that describes the attributes (file, directory, symlink, and so on) of the file specified by path, or nil if an error occurred. The keys in the dictionary are described in “File Attribute Keys”.
Special Considerations
If the item at the path is a symbolic link—that is, the value of the NSFileType key in the attributes dictionary is NSFileTypeSymbolicLink—you can use the destinationOfSymbolicLinkAtPath:error: method to retrieve the path of the item pointed to by the link. You can also use the stringByResolvingSymlinksInPath method of NSString to resolve links in the path before retrieving the item’s attributes.
As a convenience, NSDictionary provides a set of methods (declared as a category on NSDictionary) for quickly and efficiently obtaining attribute information from the returned dictionary: fileGroupOwnerAccountName, fileModificationDate, fileOwnerAccountName, filePosixPermissions, fileSize, fileSystemFileNumber, fileSystemNumber, and fileType.
Availability
- Available in OS X v10.5 and later.
See Also
Declared In
NSFileManager.hchangeCurrentDirectoryPath:
Changes the path of the current working directory to the specified 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. Changing the current working directory affects only paths created in the current process.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hcomponentsToDisplayForPath:
Returns an array of strings representing the user-visible components of a given 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 OS X v10.2 and later.
Declared In
NSFileManager.hcontainerURLForSecurityApplicationGroupIdentifier:
Returns the container directory associated with the specified security application group ID.
Discussion
As explained in App Sandbox Design Guide, groups of sandboxed apps that need to share files and other information can request a container directory as part of their entitlements. These directories are stored in ~/Library/Group Containers/.
When called with a valid group identifier, this method returns the location of that directory as an NSURL object. This method also creates the directory if it does not yet exist.
Availability
- Available in OS X v10.8 and later.
Declared In
NSFileManager.hcontentsAtPath:
Returns the contents of the file at the specified path.
Parameters
- path
The path of the file whose contents you want.
Return Value
An NSData object with the contents of the file. If path specifies a directory, or if some other error occurs, this method returns nil.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hcontentsEqualAtPath:andPath:
Returns a Boolean value that indicates whether the files or directories in specified paths have the same contents.
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 OS X v10.0 and later.
See Also
Declared In
NSFileManager.hcontentsOfDirectoryAtPath:error:
Performs a shallow search of the specified directory and returns the paths of any contained items.
Parameters
- path
The path to the directory whose contents you want to enumerate.
- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
An array of NSString objects, each of which identifies a file, directory, or symbolic link contained in path. Returns an empty array if the directory exists but has no contents. If an error occurs, this method returns nil and assigns an appropriate error object to the error parameter
Discussion
This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”), or resource forks (files that begin with “._”) but it does return other hidden files (files that begin with a period character). If you need to perform a deep enumeration, use the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: method instead.
The order of the files in the returned array is undefined.
Availability
- Available in OS X v10.5 and later.
See Also
Declared In
NSFileManager.hcontentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:
Performs a shallow search of the specified directory and returns URLs for the contained items.
Parameters
- url
The URL for the directory whose contents you want to enumerate.
- keys
An array of keys that identify the file properties that you want pre-fetched for each item in the directory. For each returned URL, the specified properties are fetched and cached in the
NSURLobject. For a list of keys you can specify, seeCommon File System Resource Keys.- mask
Options for the enumeration. Because this method performs only shallow enumerations, options that prevent descending into subdirectories or packages are not allowed; the only supported option is
NSDirectoryEnumerationSkipsHiddenFiles.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
An array of NSURL objects, each of which identifies a file, directory, or symbolic link contained in url. If the directory contains no entries, this method returns an empty array. If an error occurs, this method returns nil and assigns an appropriate error object to the error parameter.
Discussion
This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”), or resource forks (files that begin with “._”) but it does return other hidden files (files that begin with a period character). If you need to perform a deep enumeration, use the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: method instead.
The order of the files in the returned array is undefined.
Availability
- Available in OS X v10.6 and later.
See Also
Declared In
NSFileManager.hcopyItemAtPath:toPath:error:
Copies the item at the specified path to a new location synchronously.
Parameters
- srcPath
The path to the file or directory you want to move. This parameter must not be
nil.- dstPath
The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. This parameter must not be
nil.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the item was copied successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred.
Discussion
When copying items, the current process must have permission to read the file or directory at srcPath and write the parent directory of dstPath. If the item at srcPath is a directory, this method copies the directory and all of its contents, including any hidden files. If a file with the same name already exists at dstPath, this method aborts the copy attempt and returns an appropriate error. If the last component of srcPath is a symbolic link, only the link is copied to the new path.
Prior to copying an item, the file manager asks its delegate if it should actually do so for each item. It does this by calling the fileManager:shouldCopyItemAtURL:toURL: method; if that method is not implemented it calls the fileManager:shouldCopyItemAtPath:toPath: method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager copies the given file or directory. If there is an error copying an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:copyingItemAtURL:toURL: or fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: method to determine how to proceed.
Availability
- Available in OS X v10.5 and later.
Declared In
NSFileManager.hcopyItemAtURL:toURL:error:
Copies the file at the specified URL to a new location synchronously.
Parameters
- srcURL
The file URL that identifies the file you want to copy. The URL in this parameter must not be a file reference URL. This parameter must not be
nil.- dstURL
The URL at which to place the copy of srcURL. The URL in this parameter must not be a file reference URL and must include the name of the file in its new location. This parameter must not be
nil.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the item was copied successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred.
Discussion
When copying items, the current process must have permission to read the file or directory at srcURL and write the parent directory of dstURL. If the item at srcURL is a directory, this method copies the directory and all of its contents, including any hidden files. If a file with the same name already exists at dstURL, this method aborts the copy attempt and returns an appropriate error. If the last component of srcURL is a symbolic link, only the link is copied to the new path.
Prior to copying each item, the file manager asks its delegate if it should actually do so. It does this by calling the fileManager:shouldCopyItemAtURL:toURL: method; if that method is not implemented (or the process is running in OS X 10.5 or earlier) it calls the fileManager:shouldCopyItemAtPath:toPath: method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager proceeds to copy the file or directory. If there is an error copying an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:copyingItemAtURL:toURL: or fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: method to determine how to proceed.
Availability
- Available in OS X v10.6 and later.
Declared In
NSFileManager.hcreateDirectoryAtPath:withIntermediateDirectories:attributes:error:
Creates a directory with given attributes at the specified path.
Parameters
- path
A path string identifying the directory to create. You may specify a full path or a path that is relative to the current working directory. This parameter must not be
nil.- createIntermediates
If
YES, this method creates any non-existent parent directories as part of creating the directory in url. IfNO, this method fails if any of the intermediate parent directories does not exist. This method also fails if any of the intermediate path elements corresponds to a file and not a directory.- attributes
The file attributes for the new directory and any newly created intermediate directories. You can set the owner and group numbers, file permissions, and modification date. If you specify
nilfor this parameter or omit a particular value, one or more default values are used as described in the discussion. For a list of keys you can include in this dictionary, see “Constants” section lists the global constants used as keys in the attributes dictionary. Some of the keys, such asNSFileHFSCreatorCodeandNSFileHFSTypeCode, do not apply to directories.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the directory was created, YES if createIntermediates is set and the directory already exists), or NO if an error occurred.
Discussion
If you specify nil for the attributes parameter, this method uses a default set of values for the owner, group, and permissions of any newly created directories in the path. Similarly, if you omit a specific attribute, the default value is used. The default values for newly created directories are as follows:
Permissions are set according to the umask of the current process. For more information, see
umask.The owner ID is set to the effective user ID of the process.
The group ID is set to that of the parent directory.
Availability
- Available in OS X v10.5 and later.
See Also
Declared In
NSFileManager.hcreateDirectoryAtURL:withIntermediateDirectories:attributes:error:
Creates a directory with the given attributes at the specified URL.
Parameters
- url
A file URL that specifies the directory to create. If you want to specify a relative path, you must set the current working directory before creating the corresponding
NSURLobject. This parameter must not benil.- createIntermediates
If
YES, this method creates any non-existent parent directories as part of creating the directory in url. IfNO, this method fails if any of the intermediate parent directories does not exist.- attributes
The file attributes for the new directory. You can set the owner and group numbers, file permissions, and modification date. If you specify
nilfor this parameter, the directory is created according to theumask(2) OS X Developer Tools Manual Pageof the process. The “Constants” section lists the global constants used as keys in the attributes dictionary. Some of the keys, such asNSFileHFSCreatorCodeandNSFileHFSTypeCode, do not apply to directories.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the directory was created, YES if createIntermediates is set and the directory already exists), or NO if an error occurred.
Discussion
If you specify nil for the attributes parameter, this method uses a default set of values for the owner, group, and permissions of any newly created directories in the path. Similarly, if you omit a specific attribute, the default value is used. The default values for newly created directories are as follows:
Permissions are set according to the umask of the current process. For more information, see
umask.The owner ID is set to the effective user ID of the process.
The group ID is set to that of the parent directory.
If you want to specify a relative path for url, you must set the current working directory before creating the corresponding NSURL object.
Availability
- Available in OS X v10.7 and later.
See Also
Declared In
NSFileManager.hcreateFileAtPath:contents:attributes:
Creates a file with the specified content and attributes at the given location.
Parameters
- path
The path for the new file.
- contents
A data object containing the contents of the new file.
- attributes
A dictionary containing the attributes to associate with the new file. You can use these attributes to set the owner and group numbers, file permissions, and modification date. For a list of keys, see “File Attribute Keys.” If you specify
nilfor attributes, the file is created with a set of default attributes.
Return Value
YES if the operation was successful or if the item already exists, otherwise NO.
Discussion
If you specify nil for the attributes parameter, this method uses a default set of values for the owner, group, and permissions of any newly created directories in the path. Similarly, if you omit a specific attribute, the default value is used. The default values for newly created files are as follows:
Permissions are set according to the umask of the current process. For more information, see
umask.The owner ID is set to the effective user ID of the process.
The group ID is set to that of the parent directory.
If a file already exists at path, this method overwrites the contents of that file if the current process has the appropriate privileges to do so.
Availability
- Available in OS X v10.0 and later.
See Also
Declared In
NSFileManager.hcreateSymbolicLinkAtPath:withDestinationPath:error:
Creates a symbolic link that points to the specified destination.
Parameters
- path
The path at which to create the new symbolic link. The last path component is used as the name of the link.
- destPath
The path that contains the item to be pointed to by the link. In other words, this is the destination of the link.
- error
If an error occurs, upon return contains an
NSErrorobject that describes the problem. PassNULLif you do not want error information.
Return Value
YES if the symbolic link was created or NO if an error occurred. This method also returns NO if a file, directory, or link already exists at path.
Discussion
This method does not traverse symbolic links contained in destPath, making it possible to create symbolic links to locations that do not yet exist. Also, if the final path component in path is a symbolic link, that link is not followed.
Availability
- Available in OS X v10.5 and later.
Declared In
NSFileManager.hcreateSymbolicLinkAtURL:withDestinationURL:error:
Creates a symbolic link at the specified URL that points to an item at the given URL.
Parameters
- url
The file URL at which to create the new symbolic link. The last path component of the URL issued as the name of the link.
- destURL
The file URL that contains the item to be pointed to by the link. In other words, this is the destination of the link.
- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the symbolic link was created or NO if an error occurred. This method also returns NO if a file, directory, or link already exists at path.
Discussion
This method does not traverse symbolic links contained in destPath, making it possible to create symbolic links to locations that do not yet exist. Also, if the final path component in path is a symbolic link, that link is not followed.
Availability
- Available in OS X v10.7 and later.
Declared In
NSFileManager.hcurrentDirectoryPath
Returns the path of the program’s current directory.
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 OS X v10.0 and later.
See Also
Declared In
NSFileManager.hdelegate
Returns the delegate for the receiver.
Return Value
The delegate for the receiver.
Availability
- Available in OS X v10.5 and later.
Declared In
NSFileManager.hdestinationOfSymbolicLinkAtPath:error:
Returns the path of the item pointed to by a symbolic link.
Parameters
- path
The path of a file or directory.
- error
If an error occurs, upon return contains an
NSErrorobject that describes the problem. PassNULLif 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 OS X v10.5 and later.
Declared In
NSFileManager.hdisplayNameAtPath:
Returns the display name of the file or directory at a specified 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
Display names are user-friendly names for files. They are typically used to localize standard file and directory names according to the user’s language settings. They may also reflect other modifications, such as the removal of filename extensions. Such modifications are used only when displaying the file or directory to the user and do not reflect the actual path to the item in the file system. For example, if the current user’s preferred language is French, the following code fragment logs the name Bibliothèque and not the name Library, which is the actual name of the directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); |
if ([paths count] > 0) |
{ |
NSString *documentsDirectory = [paths objectAtIndex:0]; |
NSFileManager *fileManager = [[NSFileManager alloc] init]; |
NSString *displayNameAtPath = [fileManager displayNameAtPath:documentsDirectory]; |
NSLog(@"%@", displayNameAtPath); |
[fileManager release]; |
} |
Availability
- Available in OS X v10.1 and later.
Declared In
NSFileManager.henumeratorAtPath:
Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified 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 *docsDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"]; |
NSFileManager *localFileManager=[[NSFileManager alloc] init]; |
NSDirectoryEnumerator *dirEnum = |
[localFileManager enumeratorAtPath:docsDir]; |
NSString *file; |
while ((file = [dirEnum nextObject])) { |
if ([[file pathExtension] isEqualToString: @"doc"]) { |
// process the document |
[self scanDocument: [docsDir stringByAppendingPathComponent:file]]; |
} |
} |
[localFileManager release]; |
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 OS X v10.0 and later.
See Also
Declared In
NSFileManager.henumeratorAtURL:includingPropertiesForKeys:options:errorHandler:
Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified URL.
Parameters
- url
The location of the directory for which you want an enumeration. This URL must not be a symbolic link that points to the desired directory. You can use the
URLByResolvingSymlinksInPathmethod to resolve any symlinks in the URL.- keys
An array of keys that identify the properties that you want pre-fetched for each item in the enumeration. The values for these keys are cached in the corresponding
NSURLobjects. You may specifynilfor this parameter. For a list of keys you can specify, seeCommon File System Resource Keys.- mask
Options for the enumeration. For a list of valid options, see “Directory Enumeration Options.”
- handler
An optional
'errorHandler'block argument to call when an error occurs. The url parameter specifies the item for which the error occurred and the error parameter contains the error information. Your handler should returnYESwhen it wants the enumeration to continue orNOwhen it wants the enumeration to stop.
Return Value
An NSDirectoryEnumerator object that enumerates the contents of the directory at url. 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.
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).
This code fragment enumerates a URL and its subdirectories, collecting the URLs of files (skips directories). It also demonstrates how to ignore the contents of specified directories, in this case directories named “_extras”.
-(void)scanURLIgnoringExtras:(NSURL *)directoryToScan |
{ |
// Create a local file manager instance |
NSFileManager *localFileManager=[[NSFileManager alloc] init]; |
// Enumerate the directory (specified elsewhere in your code) |
// Request the two properties the method uses, name and isDirectory |
// Ignore hidden files |
// The errorHandler: parameter is set to nil. Typically you'd want to present a panel |
NSDirectoryEnumerator *dirEnumerator = [localFileManager enumeratorAtURL:directoryToScan |
includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, |
NSURLIsDirectoryKey,nil] |
options:NSDirectoryEnumerationSkipsHiddenFiles |
errorHandler:nil]; |
// An array to store the all the enumerated file names in |
NSMutableArray *theArray=[NSMutableArray array]; |
// Enumerate the dirEnumerator results, each value is stored in allURLs |
for (NSURL *theURL in dirEnumerator) { |
// Retrieve the file name. From NSURLNameKey, cached during the enumeration. |
NSString *fileName; |
[theURL getResourceValue:&fileName forKey:NSURLNameKey error:NULL]; |
// Retrieve whether a directory. From NSURLIsDirectoryKey, also |
// cached during the enumeration. |
NSNumber *isDirectory; |
[theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL]; |
// Ignore files under the _extras directory |
if (([fileName caseInsensitiveCompare:@"_extras"]==NSOrderedSame) && |
([isDirectory boolValue]==YES)) |
{ |
[dirEnumerator skipDescendants]; |
} |
else |
{ |
// Add full path for non directories |
if ([isDirectory boolValue]==NO) |
[theArray addObject:theURL]; |
} |
} |
// Do something with the path URLs. |
NSLog(@"theArray - %@",theArray); |
// Release the localFileManager. |
[localFileManager release]; |
} |
Availability
- Available in OS X v10.6 and later.
See Also
Declared In
NSFileManager.hevictUbiquitousItemAtURL:error:
Removes the local copy of the specified cloud-based item.
Parameters
- url
Specify the URL to a file or directory in iCloud storage.
- errorOut
On input, a pointer to variable for an
NSErrorobject. If an error occurs, this pointer is set to anNSErrorobject containing information about the error. You may specifynilfor this parameter if you do not want the error information.
Return Value
YES if the local item was removed successfully or NO if it was not. If NO is returned and errorOut is not nil, an NSError object describing the error is returned in that parameter.
Discussion
This method does not remove the item from the cloud. It removes only the local version. You can use this method to force iCloud to download a new version of the file or directory from the server.
To delete a file permanently from the user’s iCloud storage, use the regular NSFileManager routines for deleting files and directories. Remember that deleting items from iCloud cannot be undone. Once deleted, the item is gone forever.
Availability
- Available in OS X v10.7 and later.
Declared In
NSFileManager.hfileExistsAtPath:
Returns a Boolean value that indicates whether a file or directory exists at a specified path.
Parameters
- path
The path of the file or directory. If path begins with a tilde (
~), it must first be expanded withstringByExpandingTildeInPath, otherwise, this method returnsNO.
Return Value
YES if a file at the specified path exists or NO if the file does not exist or its existence could not be determined.
Discussion
If the file at path is inaccessible to your app, perhaps because one or more parent directories are inaccessible, this method returns 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.
Availability
- Available in OS X v10.0 and later.
See Also
Declared In
NSFileManager.hfileExistsAtPath:isDirectory:
Returns a Boolean value that indicates whether a file or directory exists at a specified path.
Parameters
- path
The path of a file or directory. If path begins with a tilde (
~), it must first be expanded withstringByExpandingTildeInPath, or this method will returnNO.- isDirectory
Upon return, contains
YESif path is a directory or if the final path element is a symbolic link that points to a directory, otherwise containsNO. If path doesn’t exist, this value is undefined upon return. PassNULLif you do not need this information.
Return Value
YES if a file at the specified path exists or NO if the file’s does not exist or its existence could not be determined.
Discussion
If the file at path is inaccessible to your app, perhaps because one or more parent directories are inaccessible, this method returns 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.
If you need to further determine if path is a package, use the isFilePackageAtPath: method of NSWorkspace.
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 alloc] init]; |
NSString *fontPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Fonts"]; |
if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir) { |
subpaths = [fileManager subpathsAtPath:fontPath]; |
// ... |
[fileManager release]; |
Availability
- Available in OS X v10.0 and later.
See Also
Declared In
NSFileManager.hfileSystemRepresentationWithPath:
Returns a C-string representation of a given path that properly encodes Unicode strings for use by the file system.
Parameters
- path
A string object containing a path to a file. This parameter must not be
nilor contain the empty string.
Return Value
A C-string representation of path that properly encodes Unicode strings for use by the file system.
Discussion
Use this method if your code calls system routines that expect C-string path arguments. If you use the C string beyond the scope of the current autorelease pool, you must copy it.
This method raises an exception if path is nil or contains the empty string. This method also throws an exception if the conversion of the string fails.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hinit
Returns an initialized NSFileManager instance.
Return Value
An initialized NSFileManager instance.
Discussion
In iOS and in OS X 10.5 and later you can use this method to create a specific file manager instance. You might do this in situations where you want to associate a delegate with the file manager to receive notifications about the status of file-related operations.
isDeletableFileAtPath:
Returns a Boolean value that indicates whether the invoking object appears able to delete a specified file.
Parameters
- path
A file path.
Return Value
YES if the current process has delete privileges for the file at path; otherwise NO if the process does not have delete privileges or the existence of the file could not be determined.
Discussion
For a directory or file to be deletable, the current process must either be able to write to the parent directory of path or it must have the same owner as the item at path. If path is a directory, every item contained in path must be deletable by the current process.
If the file at path is inaccessible to your app, perhaps because it does not have search privileges for one or more parent directories, this method returns NO. If the item at path is a symbolic link, it is not traversed.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hisExecutableFileAtPath:
Returns a Boolean value that indicates whether the operating system appears able to execute a specified file.
Parameters
- path
A file path.
Return Value
YES if the current process has execute privileges for the file at path; otherwise NO if the process does not have execute privileges or the existence of the file could not be determined.
Discussion
If the file at path is inaccessible to your app, perhaps because it does not have search privileges for one or more parent directories, this method returns NO. This method traverses symbolic links in the path. This method also uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is executable.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hisReadableFileAtPath:
Returns a Boolean value that indicates whether the invoking object appears able to read a specified file.
Parameters
- path
A file path.
Return Value
YES if the current process has read privileges for the file at path; otherwise NO if the process does not have read privileges or the existence of the file could not be determined.
Discussion
If the file at path is inaccessible to your app, perhaps because it does not have search privileges for one or more parent directories, this method returns NO. This method traverses symbolic links in the path. This method also uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is readable.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hisUbiquitousItemAtURL:
Returns a Boolean indicating whether the item is targeted for storage in iCloud.
Parameters
- url
Specify the URL for the file or directory whose status you want to check.
Return Value
YES if the item is targeted for iCloud storage or NO if it is not. This method also returns NO if no item exists at url.
Discussion
This method reflects only whether the item should be stored in iCloud because a call was made to the setUbiquitous:itemAtURL:destinationURL:error: method with a value of YES for its flag parameter. This method does not reflect whether the file has actually been uploaded to any iCloud servers. To determine a file’s upload status, check the NSURLUbiquitousItemIsUploadedKey attribute of the corresponding NSURL object.
Availability
- Available in OS X v10.7 and later.
Declared In
NSFileManager.hisWritableFileAtPath:
Returns a Boolean value that indicates whether the invoking object appears able to write to a specified file.
Parameters
- path
A file path.
Return Value
YES if the current process has write privileges for the file at path; otherwise NO if the process does not have write privileges or the existence of the file could not be determined.
Discussion
If the file at path is inaccessible to your app, perhaps because it does not have search privileges for one or more parent directories, this method returns NO. This method traverses symbolic links in the path. This method also uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is writable.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hlinkItemAtPath:toPath:error:
Creates a hard link between the items at the specified paths.
Parameters
- srcPath
The path that specifies the item you wish to link to. The value in this parameter must not be
nil.- dstPath
The path that identifies the location where the link will be created. The value in this parameter must not be
nil.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the hard link was created or NO if an error occurred. This method also returns NO if a file, directory, or link already exists at dstPath.
Discussion
Use this method to create hard links between files in the current file system. If srcPath is a directory, this method creates a new directory at dstPath and then creates hard links for the items in that directory. If srcPath is (or contains) a symbolic link, the symbolic link is copied to the new location and not converted to a hard link.
Prior to linking each item, the file manager asks its delegate if it should actually create the link. It does this by calling the fileManager:shouldLinkItemAtURL:toURL: method; if that method is not implemented it calls the fileManager:shouldLinkItemAtPath:toPath: method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager creates the hard link. If there is an error moving one out of several items, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:linkingItemAtURL:toURL: or fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: method to determine how to proceed.
Availability
- Available in OS X v10.5 and later.
Declared In
NSFileManager.hlinkItemAtURL:toURL:error:
Creates a hard link between the items at the specified URLs.
Parameters
- srcURL
The file URL that identifies the source of the link. The URL in this parameter must not be a file reference URL; it must specify the actual path to the item. The value in this parameter must not be
nil.- dstURL
The file URL that specifies where you want to create the hard link. The URL in this parameter must not be a file reference URL; it must specify the actual path to the item. The value in this parameter must not be
nil.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the hard link was created or NO if an error occurred. This method also returns NO if a file, directory, or link already exists at dstURL.
Discussion
Use this method to create hard links between files in the current file system. If srcURL is a directory, this method creates a new directory at srcURL and then creates hard links for the items in that directory. If srcURL is (or contains) a symbolic link, the symbolic link is copied and not converted to a hard link at dstURL.
Prior to linking each item, the file manager asks its delegate if it should actually create the link. It does this by calling the fileManager:shouldLinkItemAtURL:toURL: method; if that method is not implemented it calls the fileManager:shouldLinkItemAtPath:toPath: method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager creates the hard link. If there is an error moving one out of several items, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:linkingItemAtURL:toURL: or fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: method to determine how to proceed.
Availability
- Available in OS X v10.6 and later.
Declared In
NSFileManager.hmountedVolumeURLsIncludingResourceValuesForKeys:options:
Returns an array of URLs that identify the mounted volumes available on the computer.
Parameters
- propertyKeys
An array of keys that identify the file properties that you want pre-fetched for each volume. For each returned URL, the values for these keys are cached in the corresponding
NSURLobjects. You may specifynilfor this parameter. For a list of keys you can specify, seeCommon 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 OS X v10.6 and later.
Declared In
NSFileManager.hmoveItemAtPath:toPath:error:
Moves the file or directory at the specified path to a new location synchronously.
Parameters
- srcPath
The path to the file or directory you want to move. This parameter must not be
nil.- dstPath
The new path for the item in srcPath. This path must include the name of the file or directory in its new location. This parameter must not be
nil.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the item was moved successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred.
Discussion
When moving items, the current process must have permission to read the item at srcPath and write the parent directory of dstPath. If the item at srcPath is a directory, this method moves the directory and all of its contents, including any hidden files. If an item with the same name already exists at dstPath, this method aborts the move attempt and returns an appropriate error. If the last component of srcPath is a symbolic link, only the link is moved to the new path; the item pointed to by the link remains at its current location.
Prior to moving the item, the file manager asks its delegate if it should actually move it. It does this by calling the fileManager:shouldMoveItemAtURL:toURL: method; if that method is not implemented it calls the fileManager:shouldMoveItemAtPath:toPath: method instead. If the item being moved is a directory, the file manager notifies the delegate only for the directory itself and not for any of its contents. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager moves the file. If there is an error moving one out of several items, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:movingItemAtURL:toURL: or fileManager:shouldProceedAfterError:movingItemAtPath:toPath: method to determine how to proceed.
If the source and destination of the move operation are not on the same volume, this method copies the item first and then removes it from its current location. This behavior may trigger additional delegate notifications related to copying and removing individual items.
Availability
- Available in OS X v10.5 and later.
Declared In
NSFileManager.hmoveItemAtURL:toURL:error:
Moves the file or directory at the specified URL to a new location synchronously.
Parameters
- srcURL
The file URL that identifies the file or directory you want to move. The URL in this parameter must not be a file reference URL. This parameter must not be
nil.- dstURL
The new location for the item in srcURL. The URL in this parameter must not be a file reference URL and must include the name of the file or directory in its new location. This parameter must not be
nil.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the item was moved successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred.
Discussion
When moving items, the current process must have permission to read the item at srcURL and write the parent directory of dstURL. If the item at srcURL is a directory, this method moves the directory and all of its contents, including any hidden files. If an item with the same name already exists at dstURL, this method aborts the move attempt and returns an appropriate error. If the last component of srcURL is a symbolic link, only the link is moved to the new path; the item pointed to by the link remains at its current location.
Prior to moving the item, the file manager asks its delegate if it should actually move it. It does this by calling the fileManager:shouldMoveItemAtURL:toURL: method; if that method is not implemented it calls the fileManager:shouldMoveItemAtPath:toPath: method instead. If the item being moved is a directory, the file manager notifies the delegate only for the directory itself and not for any of its contents. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager moves the file. If there is an error moving one out of several items, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:movingItemAtURL:toURL: or fileManager:shouldProceedAfterError:movingItemAtPath:toPath: method to determine how to proceed.
If the source and destination of the move operation are not on the same volume, this method copies the item first and then removes it from its current location. This behavior may trigger additional delegate notifications related to copying and removing individual items.
Availability
- Available in OS X v10.6 and later.
Declared In
NSFileManager.hremoveItemAtPath:error:
Removes the file or directory at the specified path.
Parameters
- path
A path string indicating the file or directory to remove. If the path specifies a directory, the contents of that directory are recursively removed. You may specify
nilfor this parameter.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the item was removed successfully or if path was nil. Returns NO if an error occurred. If the delegate aborts the operation for a file, this method returns YES. However, if the delegate aborts the operation for a directory, this method returns NO.
Discussion
Prior to removing each item, the file manager asks its delegate if it should actually do so. It does this by calling the fileManager:shouldRemoveItemAtURL: method; if that method is not implemented (or the process is running in OS X 10.5 or earlier) it calls the fileManager:shouldRemoveItemAtPath: method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager proceeds to remove the file or directory. If there is an error removing an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:removingItemAtURL: or fileManager:shouldProceedAfterError:removingItemAtPath: method to determine how to proceed.
Availability
- Available in OS X v10.5 and later.
Declared In
NSFileManager.hremoveItemAtURL:error:
Removes the file or directory at the specified URL.
Parameters
- URL
A file URL specifying the file or directory to remove. If the URL specifies a directory, the contents of that directory are recursively removed. You may specify
nilfor this parameter.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the item was removed successfully or if URL was nil. Returns NO if an error occurred. If the delegate aborts the operation for a file, this method returns YES. However, if the delegate aborts the operation for a directory, this method returns NO.
Discussion
Prior to removing each item, the file manager asks its delegate if it should actually do so. It does this by calling the fileManager:shouldRemoveItemAtURL: method; if that method is not implemented (or the process is running in OS X 10.5 or earlier) it calls the fileManager:shouldRemoveItemAtPath: method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager proceeds to remove the file or directory. If there is an error removing an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:removingItemAtURL: or fileManager:shouldProceedAfterError:removingItemAtPath: method to determine how to proceed.
Availability
- Available in OS X v10.6 and later.
Declared In
NSFileManager.hreplaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:
Replaces the contents of the item at the specified URL in a manner that insures no data loss occurs.
Parameters
- originalItemURL
The item whose contents you want to replace.
- newItemURL
The item containing the new content for originalItemURL. It is recommended that you put this item in a temporary directory as provided by the OS. If a temporary directory is not available, put this item in a uniquely named directory that is in the same directory as the original item.
- backupItemName
Optional. If provided, this name is 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
NSFileManagerItemReplacementWithoutDeletingBackupItemoption is provided in options.- options
Specifies the options to use during the replacement. Typically, you pass
0for this parameter, which uses only the metadata from the new item. You can also combine the options described in “NSFileManagerItemReplacementOptions” using the C-bitwise OR operator.- resultingURL
On input, a pointer for a URL object. When the item is replaced, this pointer is set to the URL of the new item. If no new file system object is required, the URL object in this parameter may be the same passed to the originalItemURL parameter. However, if a new file system object is required, the URL object may be different. For example, replacing an RTF document with an RTFD document requires the creation of a new file.
- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
YES if the replacement was successful or NO if an error occurred.
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 and the original item is not in the original location or a temporary location, the returned error object contains a user info dictionary with the NSFileOriginalItemLocationKey key. The value assigned to that key is an NSURL object with the location of the item. The error code is one of the file-related errors described in NSError Codes.
Availability
- Available in OS X v10.6 and later.
Declared In
NSFileManager.hsetAttributes:ofItemAtPath:error:
Sets the attributes of the specified file or directory.
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
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the 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 app 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 OS X v10.5 and later.
See Also
Declared In
NSFileManager.hsetDelegate:
Sets the delegate for the receiver.
Parameters
- delegate
The delegate for the receiver. The delegate must implement the
NSFileManagerDelegateprotocol.
Discussion
It is recommended that you assign a delegate only to file manager objects that you create explicitly using the alloc/init convention.
Availability
- Available in OS X v10.5 and later.
Declared In
NSFileManager.hsetUbiquitous:itemAtURL:destinationURL:error:
Sets whether the item at the specified URL should be stored in the cloud.
Parameters
- flag
Specify
YESto move the item to iCloud orNOto remove it from iCloud (if it is there currently).- url
Specify the URL of the item (file or directory) that you want to store in iCloud.
- destinationURL
Specify the location in iCloud at which to store the file or directory. This URL must be constructed from a URL returned by the
URLForUbiquityContainerIdentifier:method, which you use to retrieve the desired iCloud container directory. The URL you specify may contain additional subdirectories so that you can organize your files hierarchically in iCloud. However, you are responsible for creating those intermediate subdirectories (using theNSFileManagerclass) in your iCloud container directory.- errorOut
On input, a pointer to variable for an
NSErrorobject. If an error occurs, this pointer is set to anNSErrorobject containing information about the error. You may specifynilfor this parameter if you do not want the error information.
Return Value
YES if the item’s status was updated successfully or NO if an error occurred. If this method returns NO and you specified a value for the errorOut parameter, this method returns an error object in the provided pointer.
Discussion
Use this method to move a file from its current location to iCloud. For files located in an app’s sandbox, this involves physically removing the file from the sandbox container. (The system extends your app’s sandbox privileges to give it access to files it moves to iCloud.) You can also use this method to move files out of iCloud and back into a local directory.
Your app must have an active file presenter object configured to monitor the specified file or directory before calling this method. When you specify YES for the flag parameter, this method attempts to move the file or directory to the cloud and returns YES if it is successful. This method also notifies your file presenter of the new location of the file so that your app can continue to operate on it.
Availability
- Available in OS X v10.7 and later.
See Also
Declared In
NSFileManager.hstartDownloadingUbiquitousItemAtURL:error:
Starts downloading (if necessary) the specified item to the local system.
Parameters
- url
Specify the URL for the file or directory in the cloud that you want to download.
- errorOut
On input, a pointer to variable for an
NSErrorobject. If an error occurs, this pointer is set to anNSErrorobject containing information about the error. You may specifynilfor this parameter if you do not want the error information.
Return Value
YES if the download started successfully or was not necessary, otherwise NO. If NO is returned and errorOut is not nil, an NSError object describing the error is returned in that parameter.
Discussion
If a cloud-based file or directory has not been downloaded yet, calling this method starts the download process. If the item exists locally, calling this method synchronizes the local copy with the version in the cloud.
For a given URL, you can determine if a file is downloaded by getting the value of the NSMetadataUbiquitousItemIsDownloadedKey key. You can also use related keys to determine the current progress in downloading the file.
Availability
- Available in OS X v10.7 and later.
Declared In
NSFileManager.hstringWithFileSystemRepresentation:length:
Returns an NSString object whose contents are derived from the specified C-string path.
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 OS X v10.0 and later.
See Also
Declared In
NSFileManager.hsubpathsAtPath:
Returns an array of strings identifying the paths for all items in the specified directory.
Parameters
- path
The path of the directory to list.
Return Value
An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file.
Discussion
This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion.
This method reveals every element of the subtree at path, including the contents of file packages (such as apps, 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 alloc] init]; |
if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir) |
subpaths = [fileManager subpathsAtPath:fontPath]; |
[fileManager release]; |
Special Considerations
On OS X v10.5 and later, use subpathsOfDirectoryAtPath:error: instead.
Availability
- Available in OS X v10.0 and later.
Declared In
NSFileManager.hsubpathsOfDirectoryAtPath:error:
Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories.
Parameters
- path
The path of the directory to list.
- error
If an error occurs, upon return contains an
NSErrorobject that describes the problem. PassNULLif you do not want error information.
Return Value
An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file.
Discussion
This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion.
Because this method recurses the directory’s contents, you might not want to use it in performance-critical code. Instead, consider using the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: or enumeratorAtPath: method to enumerate the directory contents yourself. Doing so gives you more control over the retrieval of items and more opportunities to abort the enumeration or perform other tasks at the same time.
Availability
- Available in OS X v10.5 and later.
See Also
Declared In
NSFileManager.htrashItemAtURL:resultingItemURL:error:
Moves an item to the trash.
Return Value
YES if the item at url was successfully moved to the trash. Since the operation may require renaming the item to avoid a file name collision, this method returns, by reference, the resulting URL that the item was moved to.
If this method returns NO, the item was not moved to the trash; the error parameter then contains information about the error.
Availability
- Available in OS X v10.8 and later.
Declared In
NSFileManager.hubiquityIdentityToken
Returns an opaque token that represents the current iCloud (“ubiquity”) identity.
Return Value
An opaque object that identifies the current iCloud user. If iCloud is unavailable for any reason or there is no logged-in user, this method returns nil.
Discussion
Use this method to determine if iCloud is currently available. Because this method returns relatively quickly, you can call it at launch time and you can call it from your app’s main thread.
You can use the token returned by this method, together with the NSUbiquityIdentityDidChangeNotification notification, to detect when the user logs in or out of iCloud and to detect changes to the active iCloud account. When the user logs in with a different iCloud account, the returned identity token changes and the system posts the notification. If you stored or archived the previous token, you compare that token to the newly obtained one using the isEqual: method to determine if the users are the same or different.
Calling this method does not establish access to your app’s ubiquity containers. To establish access to a ubiquity container, call the URLForUbiquityContainerIdentifier: method. In OS X, you can instead use an NSDocument object, which establishes access automatically.
Availability
- Available in OS X v10.8 and later.
See Also
Declared In
NSFileManager.hURLForDirectory:inDomain:appropriateForURL:create:error:
Locates and optionally creates the specified common directory in a domain.
Parameters
- directory
The search path directory. The supported values are described in
NSSearchPathDirectory.- domain
The file system domain to search. The value for this parameter is one of the constants described in
NSSearchPathDomainMask. You should specify only one domain for your search and you may not specify theNSAllDomainsMaskconstant for this parameter.- url
The name of a directory inside of which you want to create a unique temporary directory for autosaving documents or some other use. This parameter is ignored unless the directory parameter contains the value
NSItemReplacementDirectoryand the domain parameter contains the valueNSUserDomainMask. When creating a temporary directory, the shouldCreate parameter is ignored and the directory is always created.- shouldCreate
Specify
YESif you want the directory to be created if it does not exist.- error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify
nilfor this parameter if you do not want the error information.
Return Value
The NSURL for the requested directory or nil if an error occurred.
Discussion
You typically use this method to locate one of the standard system directories, such as the Documents, Application Support or Caches directories. You can also use this method to create a new temporary directory for storing things like autosave files; to do so, specify NSItemReplacementDirectory for the directory parameter, NSUserDomainMask for the domain parameter, and a valid parent directory for the url parameter. After locating (or creating) the desired directory, this method returns the URL for that directory. If more than one appropriate directory exists in the specified domain, this method returns only the first one it finds.
Passing a directory and domain pair that makes no sense (for example NSDesktopDirectory and NSNetworkDomainMask) raises an exception.
Availability
- Available in OS X v10.6 and later.
See Also
Declared In
NSFileManager.hURLForPublishingUbiquitousItemAtURL:expirationDate:error:
Returns a URL that can be emailed to users to allow them to download a copy of a cloud-based item.
Parameters
- url
Specify the URL of the item in the cloud that you want to share. The URL must be prefixed with the base URL returned from the
URLForUbiquityContainerIdentifier:method that corresponds to the item’s location.- outDate
On input, a pointer to a variable for a date object. On output, this parameter contains the date after which the item is no longer available at the returned URL. You may specify
nilfor this parameter if you are not interested in the date.- error
On input, a pointer to variable for an
NSErrorobject. If an error occurs, this pointer is set to anNSErrorobject containing information about the error. You may specifynilfor this parameter if you do not want the error information.
Return Value
A URL with which users can download a copy of the item at url. Returns nil if the URL could not be created for any reason.
Discussion
This method creates a snapshot of the specified file and places that copy in a temporary iCloud location where it can be accessed by other users using the returned URL. The snapshot reflects the contents of the file at the time the URL was generated and is not updated when subsequent changes are made to the original file in the user’s iCloud storage. The snapshot file remains available at the specified URL until the date specified in the outDate parameter, after which it is automatically deleted.
Your app must have access to the network for this call to succeed.
Availability
- Available in OS X v10.7 and later.
See Also
Declared In
NSFileManager.hURLForUbiquityContainerIdentifier:
Returns the URL for the ubiquity (iCloud) container associated with the specified container identifier, and establishes access to that container.
Parameters
- containerID
The fully-qualified container identifier for a ubiquity container. The string you specify must not contain wildcards and must be of the form <TEAMID>
.<CONTAINER>, where <TEAMID> is your development team ID and <CONTAINER> describes the bundle identifier of the container you want to access.The container identifiers for your app must be declared in the
com.apple.developer.ubiquity-container-identifiersarray of the.entitlementsproperty list file in your Xcode project.If you specify
nilin this parameter, this method returns the first container listed in thecom.apple.developer.ubiquity-container-identifiersentitlement array.
Return Value
A URL pointing to the specified ubiquity container, or nil if the container could not be located or if iCloud storage is unavailable for the current user or device.
Discussion
You use this method to determine the location of your app’s ubiquity container directories and to configure your app’s initial iCloud access. The first time you call this method for a given ubiquity container, the system extends your app’s sandbox to include that container. In iOS, you must call this method at least once before trying to search for cloud-based files in the ubiquity container. If your app accesses multiple ubiquity containers, call this method once for each container. In OS X, you do not need to call this method if you use NSDocument-based objects, because the system then calls this method automatically.
You can use the URL returned by this method to build paths to files and directories within your app’s ubiquity container. Each app that syncs documents to the cloud must have at least one associated ubiquity container in which to put those files. This container can be unique to the app or shared by multiple apps.
In addition to writing to its own ubiquity container, an app can write to any container directory for which it has the appropriate permission. Each additional ubiquity container should be listed as an additional value in the com.apple.developer.ubiquity-container-identifiers entitlement array.
To learn how to view your development team’s unique <TEAM_ID> value, read “To view the team ID…” in Tools Workflow Guide for Mac.
Availability
- Available in OS X v10.7 and later.
Declared In
NSFileManager.hURLsForDirectory:inDomains:
Returns an array of URLs for the specified common directory in the requested domains.
Parameters
- directory
The search path directory. The supported values are described in
NSSearchPathDirectory.- domainMask
The file system domain to search. The value for this parameter is one or more of the constants described in
NSSearchPathDomainMask.
Return Value
An array of NSURL objects identifying the requested directories. The directories are ordered according to the order of the domain mask constants, with items in the user domain first and items in the system domain last.
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 OS X v10.6 and later.
Declared In
NSFileManager.hConstants
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
NSVolumeEnumerationSkipHiddenVolumesThe enumeration skips hidden volumes.
Available in OS X v10.6 and later.
Declared in
NSFileManager.h.NSVolumeEnumerationProduceFileReferenceURLsThe enumeration produces file reference URLs rather than path-based URLs.
Available in 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
NSDirectoryEnumerationSkipsSubdirectoryDescendantsPerform a shallow enumeration; do not descend into directories.
Available in OS X v10.6 and later.
Declared in
NSFileManager.h.NSDirectoryEnumerationSkipsPackageDescendantsDo not descend into packages.
Available in OS X v10.6 and later.
Declared in
NSFileManager.h.NSDirectoryEnumerationSkipsHiddenFilesDo not enumerate hidden files.
Available in OS X v10.6 and later.
Declared in
NSFileManager.h.
NSFileManagerItemReplacementOptions
The constants specify the replacement behavior in replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:.
enum {
NSFileManagerItemReplacementUsingNewMetadataOnly = 1UL << 0,
NSFileManagerItemReplacementWithoutDeletingBackupItem = 1UL << 1
};
typedef NSUInteger NSFileManagerItemReplacementOptions;
Constants
NSFileManagerItemReplacementUsingNewMetadataOnlyCauses
replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:to use metadata from the new item only and not to attempt to preserve metadata from the original item.Available in OS X v10.6 and later.
Declared in
NSFileManager.h.NSFileManagerItemReplacementWithoutDeletingBackupItemCauses
replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:to leave the backup item in place after a successful replacement. The default behavior is to remove the item.Available in 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
NSFileAppendOnlyThe key in a file attribute dictionary whose value indicates whether the file is read-only.
The corresponding value is an
NSNumberobject containing a Boolean value.Available in OS X v10.2 and later.
Declared in
NSFileManager.h.NSFileBusyThe key in a file attribute dictionary whose value indicates whether the file is busy.
The corresponding value is an
NSNumberobject containing a Boolean value.Available in OS X v10.4 and later.
Declared in
NSFileManager.h.NSFileCreationDateThe key in a file attribute dictionary whose value indicates the file's creation date.
The corresponding value is an
NSDateobject.Available in OS X v10.2 and later.
Declared in
NSFileManager.h.NSFileOwnerAccountNameThe key in a file attribute dictionary whose value indicates the name of the file's owner.
The corresponding value is an
NSStringobject.Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileGroupOwnerAccountNameThe key in a file attribute dictionary whose value indicates the group name of the file's owner.
The corresponding value is an
NSStringobject.Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileDeviceIdentifierThe key in a file attribute dictionary whose value indicates the identifier for the device on which the file resides.
The corresponding value is an
NSNumberobject containing anunsigned long.Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileExtensionHiddenThe key in a file attribute dictionary whose value indicates whether the file's extension is hidden.
The corresponding value is an
NSNumberobject containing a Boolean value.Available in OS X v10.1 and later.
Declared in
NSFileManager.h.NSFileGroupOwnerAccountIDThe key in a file attribute dictionary whose value indicates the file's group ID.
The corresponding value is an
NSNumberobject containing anunsigned long.Available in OS X v10.2 and later.
Declared in
NSFileManager.h.NSFileHFSCreatorCodeThe key in a file attribute dictionary whose value indicates the file's HFS creator code.
The corresponding value is an
NSNumberobject containing anunsigned long. See “HFS File Types” for possible values.Available in OS X v10.1 and later.
Declared in
NSFileManager.h.NSFileHFSTypeCodeThe key in a file attribute dictionary whose value indicates the file's HFS type code.
The corresponding value is an
NSNumberobject containing anunsigned long. See “HFS File Types” for possible values.Available in OS X v10.1 and later.
Declared in
NSFileManager.h.NSFileImmutableThe key in a file attribute dictionary whose value indicates whether the file is mutable.
The corresponding value is an
NSNumberobject containing a Boolean value.Available in OS X v10.2 and later.
Declared in
NSFileManager.h.NSFileModificationDateThe key in a file attribute dictionary whose value indicates the file's last modified date.
The corresponding value is an
NSDateobject.Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileOwnerAccountIDThe key in a file attribute dictionary whose value indicates the file's owner's account ID.
The corresponding value is an
NSNumberobject containing anunsigned long.Available in OS X v10.2 and later.
Declared in
NSFileManager.h.NSFilePosixPermissionsThe key in a file attribute dictionary whose value indicates the file's Posix permissions.
The corresponding value is an
NSNumberobject. Use theshortValuemethod to retrieve the integer value for the permissions.Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileReferenceCountThe key in a file attribute dictionary whose value indicates the file's reference count.
The corresponding value is an
NSNumberobject containing anunsigned long.The number specifies the number of hard links to a file.
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileSizeThe key in a file attribute dictionary whose value indicates the file's size in bytes.
The corresponding value is an
NSNumberobject containing anunsigned long long.Important: If the file has a resource fork, the returned value does not include the size of the resource fork.
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileSystemFileNumberThe key in a file attribute dictionary whose value indicates the file's filesystem file number.
The corresponding value is an
NSNumberobject containing anunsigned long. The value corresponds to the value ofst_ino, as returned bystat(2).Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileTypeThe key in a file attribute dictionary whose value indicates the file's type.
The corresponding value is an
NSStringobject (see “NSFileType Attribute Values” for possible values).Available in 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.hNSFileType Attribute Values
These strings are the possible values for the NSFileType attribute key contained in the dictionary 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
NSFileTypeDirectoryDirectory
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileTypeRegularRegular file
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileTypeSymbolicLinkSymbolic link
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileTypeSocketSocket
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileTypeCharacterSpecialCharacter special file
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileTypeBlockSpecialBlock special file
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileTypeUnknownUnknown
Available in OS X v10.0 and later.
Declared in
NSFileManager.h.
File-System Attribute Keys
Keys to access the file attribute values contained in the dictionary object returned from the attributesOfFileSystemForPath:error: method.
extern NSString *NSFileSystemSize; extern NSString *NSFileSystemFreeSize; extern NSString *NSFileSystemNodes; extern NSString *NSFileSystemFreeNodes; extern NSString *NSFileSystemNumber;
Constants
NSFileSystemSizeThe key in a file system attribute dictionary whose value indicates the size of the file system.
The corresponding value is an
NSNumberobject that specifies the size of the file system in bytes. The value is determined bystatfs().Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileSystemFreeSizeThe key in a file system attribute dictionary whose value indicates the amount of free space on the file system.
The corresponding value is an
NSNumberobject that specifies the amount of free space on the file system in bytes. The value is determined bystatfs().Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileSystemNodesThe key in a file system attribute dictionary whose value indicates the number of nodes in the file system.
The corresponding value is an
NSNumberobject that specifies the number of nodes in the file system.Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileSystemFreeNodesThe 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
NSNumberobject that specifies the number of free nodes in the file system.Available in OS X v10.0 and later.
Declared in
NSFileManager.h.NSFileSystemNumberThe key in a file system attribute dictionary dictionary whose value indicates the filesystem number of the file system.
The corresponding value is an
NSNumberobject that specifies the filesystem number of the file system. The value corresponds to the value ofst_dev, as returned bystat(2).Available in 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
NSFoundationVersionWithFileManagerResourceForkSupportThe version of the Foundation framework in which
NSFileManagerfirst supported resource forks.Available in OS X v10.1 and later.
Declared in
NSFileManager.h.
Declared In
NSFileManager.hNotifications
NSUbiquityIdentityDidChangeNotification
When your app receives this notification, call the ubiquityIdentityToken method to obtain a token that represents the new ubiquity identity, or nil if the user has disabled iCloud. There is no userInfo dictionary.
Availability
- Available in OS X v10.8 and later.
Declared In
NSFileManager.h© 2013 Apple Inc. All Rights Reserved. (Last updated: 2013-03-14)