NSFileManager
An NSFileManager object lets you examine the contents of the file system and make changes to it. A file manager object is usually your first interaction with the file system. You use it to locate, create, copy, and move files and directories. You also use it to get information about a file or directory or change some of its attributes.
The NSFileManager class provides convenient access to a shared file manager object that is suitable for most types of file-related manipulations. If you plan to use the file manager object interactively—for example, if you plan to assign a delegate object to it—create your own instance of the class.
When specifying the location of files, you can use either NSURL or NSString objects. 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 iCloud. 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.
-
Returns an initialized
NSFileManagerinstance.Declaration
Objective-C
- initReturn Value
An initialized
NSFileManagerinstance.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.
-
Returns the shared file manager object for the process.
Declaration
Swift
class func defaultManager() -> NSFileManagerObjective-C
+ (NSFileManager *)defaultManagerReturn Value
The default
NSFileManagerobject 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 theinitmethod) rather than using the shared object.Availability
Available in OS X v10.0 and later.
-
URLForDirectory(_:inDomain:appropriateForURL:create:) - URLForDirectory:inDomain:appropriateForURL:create:error:Locates and optionally creates the specified common directory in a domain.
Declaration
Swift
func URLForDirectory(_directory: NSSearchPathDirectory, inDomaindomain: NSSearchPathDomainMask, appropriateForURLurl: NSURL?, createshouldCreate: Bool) throws -> NSURLObjective-C
- (NSURL *)URLForDirectory:(NSSearchPathDirectory)directoryinDomain:(NSSearchPathDomainMask)domainappropriateForURL:(NSURL *)urlcreate:(BOOL)shouldCreateerror:(NSError * _Nullable *)errorParameters
directoryThe search path directory. The supported values are described in
NSSearchPathDirectory.domainThe 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.urlThe file URL used to determine the location of the returned URL. Only the volume of this parameter is used.
This parameter is ignored unless the
directoryparameter contains the valueNSItemReplacementDirectoryand thedomainparameter contains the valueNSUserDomainMask.shouldCreateWhether to create the directory if it does not already exist.
When creating a temporary directory, this parameter is ignored and the directory is always created.
errorOn 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
NSURLfor the requested directory ornilif an error occurred.Discussion
You typically use this method to locate one of the standard system directories, such as the
Documents,Application SupportorCachesdirectories. 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.You can use this method to create a new temporary directory. To do so, specify
NSItemReplacementDirectoryfor thedirectoryparameter,NSUserDomainMaskfor thedomainparameter, and a URL for theurlparamer which determines the volume of the returned URL.For example, the following code results in
temporaryDirectoryURLwith a value in the form of/private/var/folders/d0/h37cw8ns3h1bfr_2gnwq2yyc0000gn/T/TemporaryItems/Untitled/:Objective-C
NSURL *desktopURL = [NSURL fileURLWithPath:@"/Users/jappleseed/Desktop/"isDirectory:YES];NSError *error = nil;NSURL *temporaryDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSItemReplacementDirectoryinDomain:NSUserDomainMaskappropriateForURL:parentURLcreate:YESerror:&error];if (error) {// handle the error}
Swift
let desktopURL = NSURL(fileURLWithPath: "/Users/jappleseed/Desktop/")do {let temporaryDirectoryURL = try NSFileManager.defaultManager().URLForDirectory(.ItemReplacementDirectory, inDomain: .UserDomainMask, appropriateForURL: desktopURL, create: true)} catch {// handle the error}
Availability
Available in OS X v10.6 and later.
See Also
-
Returns an array of URLs for the specified common directory in the requested domains.
Declaration
Swift
func URLsForDirectory(_directory: NSSearchPathDirectory, inDomainsdomainMask: NSSearchPathDomainMask) -> [NSURL]Objective-C
- (NSArray<NSURL *> *)URLsForDirectory:(NSSearchPathDirectory)directoryinDomains:(NSSearchPathDomainMask)domainMaskParameters
directoryThe search path directory. The supported values are described in
NSSearchPathDirectory.domainMaskThe 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
NSURLobjects 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 theNSSearchPathDirectory, including:NSDesktopDirectory,NSApplicationSupportDirectory, and many more.Availability
Available in OS X v10.6 and later.
-
containerURLForSecurityApplicationGroupIdentifier(_:) - containerURLForSecurityApplicationGroupIdentifier:Returns the container directory associated with the specified security application group ID.
Declaration
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
NSURLobject. This method also creates the directory if it does not yet exist.Availability
Available in OS X v10.8 and later.
-
contentsOfDirectoryAtURL(_:includingPropertiesForKeys:options:) - contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:Performs a shallow search of the specified directory and returns URLs for the contained items.
Declaration
Swift
func contentsOfDirectoryAtURL(_url: NSURL, includingPropertiesForKeyskeys: [String]?, optionsmask: NSDirectoryEnumerationOptions) throws -> [NSURL]Parameters
urlThe URL for the directory whose contents you want to enumerate.
keysAn 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.If you want directory contents to have no pre-fetched file properties, pass an empty array to this parameter. If you want directory contents to have default set of pre-fetched file properties, pass
nilto this parameter.maskOptions 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.errorOn 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
NSURLobjects, each of which identifies a file, directory, or symbolic link contained inurl. If the directory contains no entries, this method returns an empty array. If an error occurs, this method returnsniland assigns an appropriate error object to theerrorparameter.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 theenumeratorAtURL: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
-
Performs a shallow search of the specified directory and returns the paths of any contained items.
Declaration
Parameters
pathThe path to the directory whose contents you want to enumerate.
errorOn 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
NSStringobjects, each of which identifies a file, directory, or symbolic link contained inpath. Returns an empty array if the directory exists but has no contents. If an error occurs, this method returnsniland assigns an appropriate error object to theerrorparameterDiscussion
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 theenumeratorAtURL: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.
-
enumeratorAtURL(_:includingPropertiesForKeys:options:errorHandler:) - enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified URL.
Declaration
Swift
func enumeratorAtURL(_url: NSURL, includingPropertiesForKeyskeys: [String]?, optionsmask: NSDirectoryEnumerationOptions, errorHandlerhandler: ((NSURL, NSError) -> Bool)?) -> NSDirectoryEnumerator?Objective-C
- (NSDirectoryEnumerator<NSURL *> *)enumeratorAtURL:(NSURL *)urlincludingPropertiesForKeys:(NSArray<NSString *> *)keysoptions:(NSDirectoryEnumerationOptions)maskerrorHandler:(BOOL (^)(NSURL *url, NSError *error))handlerParameters
urlThe 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.keysAn 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.maskOptions for the enumeration. For a list of valid options, see NSDirectoryEnumerationOptions.
handlerAn optional error handler block for the file manager to call when an error occurs. The handler block should return
YEStrueif you want the enumeration to continue orNOfalseif you want the enumeration to stop. The block takes the following parameters:urlAn
NSURLobject that identifies the item for which the error occurred.errorAn
NSErrorobject that contains information about the error.If you specify
nilfor this parameter, the enumerator object continues to enumerator items as if you had specified a block that returnedYEStrue.Return Value
An
NSDirectoryEnumeratorobject that enumerates the contents of the directory aturl. Ifurlis a filename, the method returns an enumerator object that enumerates no files—the first call tonextObjectreturnsnil.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 or mount points encountered in the enumeration process, nor does it recurse through them if they point to a directory.
For example, if you pass a URL that points to
/Volumes/MyMountedFileSystem, the returned enumerator will include the entire directory structure for the file system mounted at that location. If, on the other hand, you pass/Volumes, the returned enumerator will include/Volumes/MyMountedFileSystemas one of its results, but will not traverse into the file system mounted there.The
NSDirectoryEnumeratorclass 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 toenumeratorAtURL: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”.
Objective-C
NSURL *directoryURL = [[NSBundle mainBundle] bundleURL];NSFileManager *localFileManager= [[NSFileManager alloc] init];NSDirectoryEnumerator *directoryEnumerator =[localFileManager enumeratorAtURL:directoryURLincludingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]options:NSDirectoryEnumerationSkipsHiddenFileserrorHandler:nil];NSMutableArray<NSURL *> *mutableFileURLs = [NSMutableArray array];for (NSURL *fileURL in directoryEnumerator) {NSNumber *isDirectory = nil;[fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];if ([isDirectory boolValue]) {NSString *name = nil;[fileURL getResourceValue:&name forKey:NSURLNameKey error:nil];if ([name isEqualToString:@"_extras"]) {[directoryEnumerator skipDescendants];} else {[mutableFileURLs addObject:fileURL];}}}NSLog(@"Files: %@", mutableFileURLs);
Swift
let directoryURL = NSBundle.mainBundle().bundleURLlet localFileManager = NSFileManager()let resourceKeys = [NSURLNameKey, NSURLIsDirectoryKey]let directoryEnumerator = localFileManager.enumeratorAtURL(directoryURL, includingPropertiesForKeys: resourceKeys, options: [.SkipsHiddenFiles], errorHandler: nil)!var fileURLs: [NSURL] = []for case let fileURL as NSURL in directoryEnumerator {guard let resourceValues = try? fileURL.resourceValuesForKeys(resourceKeys),let isDirectory = resourceValues[NSURLIsDirectoryKey] as? Bool,let name = resourceValues[NSURLNameKey] as? Stringelse {continue}if isDirectory {if name == "_extras" {directoryEnumerator.skipDescendants()}} else {fileURLs.append(fileURL)}}print(fileURLs)
Availability
Available in OS X v10.6 and later.
See Also
-
Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified path.
Declaration
Swift
func enumeratorAtPath(_path: String) -> NSDirectoryEnumerator?Objective-C
- (NSDirectoryEnumerator<NSString *> *)enumeratorAtPath:(NSString *)pathParameters
pathThe path of the directory to enumerate.
Return Value
An
NSDirectoryEnumeratorobject that enumerates the contents of the directory atpath.If
pathis a filename, the method returns an enumerator object that enumerates no files—the first call tonextObjectwill returnnil.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
Documentsdirectory 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]];}}
The
NSDirectoryEnumeratorclass 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.
-
mountedVolumeURLsIncludingResourceValuesForKeys(_:options:) - mountedVolumeURLsIncludingResourceValuesForKeys:options:Returns an array of URLs that identify the mounted volumes available on the computer.
Declaration
Swift
func mountedVolumeURLsIncludingResourceValuesForKeys(_propertyKeys: [String]?, optionsoptions: NSVolumeEnumerationOptions) -> [NSURL]?Objective-C
- (NSArray<NSURL *> *)mountedVolumeURLsIncludingResourceValuesForKeys:(NSArray<NSString *> *)propertyKeysoptions:(NSVolumeEnumerationOptions)optionsParameters
propertyKeysAn 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.optionsOption flags for the enumeration. For a list of possible values, see NSVolumeEnumerationOptions.
Return Value
An array of
NSURLobjects 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.
-
Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories.
Declaration
Parameters
pathThe path of the directory to list.
errorIf an error occurs, upon return contains an
NSErrorobject that describes the problem. PassNULLif you do not want error information.Return Value
An array of
NSStringobjects, each of which contains the path of an item in the directory specified bypath. Ifpathis a symbolic link, this method traverses the link. This method returnsnilif 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:orenumeratorAtPath:method to enumerate the directory contents yourself. Doing so gives you more control over the retrieval of items and more opportunities to complete the enumeration or perform other tasks at the same time.Availability
Available in OS X v10.5 and later.
-
Returns an array of strings identifying the paths for all items in the specified directory.
Declaration
Parameters
pathThe path of the directory to list.
Return Value
An array of
NSStringobjects, each of which contains the path of an item in the directory specified bypath. Ifpathis a symbolic link, this method traverses the link. This method returnsnilif 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/Fontsafter 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];
Special Considerations
On OS X v10.5 and later, use
subpathsOfDirectoryAtPath:error:instead.Availability
Available in OS X v10.0 and later.
-
createDirectoryAtURL(_:withIntermediateDirectories:attributes:) - createDirectoryAtURL:withIntermediateDirectories:attributes:error:Creates a directory with the given attributes at the specified URL.
Declaration
Swift
func createDirectoryAtURL(_url: NSURL, withIntermediateDirectoriescreateIntermediates: Bool, attributesattributes: [String : AnyObject]?) throwsObjective-C
- (BOOL)createDirectoryAtURL:(NSURL *)urlwithIntermediateDirectories:(BOOL)createIntermediatesattributes:(NSDictionary<NSString *,id> *)attributeserror:(NSError * _Nullable *)errorParameters
urlA 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.createIntermediatesIf
YEStrue, this method creates any non-existent parent directories as part of creating the directory inurl. IfNOfalse, this method fails if any of the intermediate parent directories does not exist.attributesThe 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) Mac OS X Developer Tools Manual Pageof the process. The Constants section lists the global constants used as keys in theattributesdictionary. Some of the keys, such asNSFileHFSCreatorCodeandNSFileHFSTypeCode, do not apply to directories.errorOn 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
YEStrueif the directory was created,YEStrueifcreateIntermediatesis set and the directory already exists, orNOfalseif an error occurred.Discussion
If you specify
nilfor theattributesparameter, 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
NSURLobject.Availability
Available in OS X v10.7 and later.
-
createDirectoryAtPath(_:withIntermediateDirectories:attributes:) - createDirectoryAtPath:withIntermediateDirectories:attributes:error:Creates a directory with given attributes at the specified path.
Declaration
Swift
func createDirectoryAtPath(_path: String, withIntermediateDirectoriescreateIntermediates: Bool, attributesattributes: [String : AnyObject]?) throwsObjective-C
- (BOOL)createDirectoryAtPath:(NSString *)pathwithIntermediateDirectories:(BOOL)createIntermediatesattributes:(NSDictionary<NSString *,id> *)attributeserror:(NSError * _Nullable *)errorParameters
pathA 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.createIntermediatesIf
YEStrue, this method creates any non-existent parent directories as part of creating the directory inpath. IfNOfalse, 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.attributesThe 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 theattributesdictionary. Some of the keys, such asNSFileHFSCreatorCodeandNSFileHFSTypeCode, do not apply to directories.errorOn 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
YEStrueif the directory was created,YEStrueifcreateIntermediatesis set and the directory already exists), orNOfalseif an error occurred.Discussion
If you specify
nilfor theattributesparameter, 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.
-
Creates a file with the specified content and attributes at the given location.
Declaration
Swift
func createFileAtPath(_path: String, contentsdata: NSData?, attributesattr: [String : AnyObject]?) -> BoolObjective-C
- (BOOL)createFileAtPath:(NSString *)pathcontents:(NSData *)contentsattributes:(NSDictionary<NSString *,id> *)attributesParameters
pathThe path for the new file.
contentsA data object containing the contents of the new file.
attributesA 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
nilforattributes, the file is created with a set of default attributes.Return Value
YEStrueif the operation was successful or if the item already exists, otherwiseNOfalse.Discussion
If you specify
nilfor theattributesparameter, 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.
-
Removes the file or directory at the specified URL.
Declaration
Swift
func removeItemAtURL(_URL: NSURL) throwsParameters
URLA 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.errorOn 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
YEStrueif the item was removed successfully or ifURLwasnil. ReturnsNOfalseif an error occurred. If the delegate stops the operation for a file, this method returnsYEStrue. However, if the delegate stops the operation for a directory, this method returnsNOfalse.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 thefileManager:shouldRemoveItemAtPath:method instead. If the delegate method returnsYEStrue, 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’sfileManager:shouldProceedAfterError:removingItemAtURL:orfileManager:shouldProceedAfterError:removingItemAtPath:method to determine how to proceed.Removing an item also removes all old versions of that item, invalidating any URLs returned by the
URLForPublishingUbiquitousItemAtURL:expirationDate:error:method to old versions.Availability
Available in OS X v10.6 and later.
-
Removes the file or directory at the specified path.
Declaration
Swift
func removeItemAtPath(_path: String) throwsParameters
pathA 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.errorOn 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
YEStrueif the item was removed successfully or ifpathwasnil. ReturnsNOfalseif an error occurred. If the delegate stops the operation for a file, this method returnsYEStrue. However, if the delegate stops the operation for a directory, this method returnsNOfalse.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 thefileManager:shouldRemoveItemAtPath:method instead. If the delegate method returnsYEStrue, 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’sfileManager:shouldProceedAfterError:removingItemAtURL:orfileManager:shouldProceedAfterError:removingItemAtPath:method to determine how to proceed.Removing an item also removes all old versions of that item, invalidating any URLs returned by the
URLForPublishingUbiquitousItemAtURL:expirationDate:error:method to old versions.Availability
Available in OS X v10.5 and later.
-
replaceItemAtURL(_:withItemAtURL:backupItemName:options:resultingItemURL:) - replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:Replaces the contents of the item at the specified URL in a manner that insures no data loss occurs.
Declaration
Swift
func replaceItemAtURL(_originalItemURL: NSURL, withItemAtURLnewItemURL: NSURL, backupItemNamebackupItemName: String?, optionsoptions: NSFileManagerItemReplacementOptions, resultingItemURLresultingURL: AutoreleasingUnsafeMutablePointer<NSURL?>) throwsParameters
originalItemURLThe item whose contents you want to replace.
newItemURLThe 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.backupItemNameOptional. 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 inoptions.optionsSpecifies the options to use during the replacement. Typically, you pass
NSFileManagerItemReplacementUsingNewMetadataOnlyfor 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.resultingURLOn 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
originalItemURLparameter. 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.errorOn 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
YEStrueif the replacement was successful orNOfalseif 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
NSFileOriginalItemLocationKeykey. The value assigned to that key is anNSURLobject with the location of the item. The error code is one of the file-related errors described inNSError Codes.Availability
Available in OS X v10.6 and later.
-
Moves an item to the trash.
Declaration
Swift
func trashItemAtURL(_url: NSURL, resultingItemURLoutResultingURL: AutoreleasingUnsafeMutablePointer<NSURL?>) throwsParameters
urlThe item to move to the trash.
outResultingURLOn input, a pointer to a URL object. On output, this pointer is set to the item’s location in the trash. The actual name of the item may be changed when moving it to the trash, so use this URL to access it. You may specify
nilfor this parameter if you do not want the information.errorOn 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
YEStrueif the item aturlwas successfully moved to the trash, orNOfalseif the item was not moved to the trash.Discussion
Availability
Available in OS X v10.8 and later.
-
Copies the file at the specified URL to a new location synchronously.
Declaration
Parameters
srcURLThe 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.dstURLThe 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 benil.errorOn 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
YEStrueif the item was copied successfully or the file manager’s delegate stopped the operation deliberately. ReturnsNOfalseif an error occurred.Discussion
When copying items, the current process must have permission to read the file or directory at
srcURLand write the parent directory ofdstURL. If the item atsrcURLis 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 atdstURL, this method stops the copy attempt and returns an appropriate error. If the last component ofsrcURLis 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 thefileManager:shouldCopyItemAtPath:toPath:method instead. If the delegate method returnsYEStrue, 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’sfileManager:shouldProceedAfterError:copyingItemAtURL:toURL:orfileManager:shouldProceedAfterError:copyingItemAtPath:toPath:method to determine how to proceed.Availability
Available in OS X v10.6 and later.
-
Copies the item at the specified path to a new location synchronously.
Declaration
Parameters
srcPathThe path to the file or directory you want to move. This parameter must not be
nil.dstPathThe 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 benil.errorOn 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
YEStrueif the item was copied successfully or the file manager’s delegate stopped the operation deliberately. ReturnsNOfalseif an error occurred.Discussion
When copying items, the current process must have permission to read the file or directory at
srcPathand write the parent directory ofdstPath. If the item atsrcPathis 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 atdstPath, this method stops the copy attempt and returns an appropriate error. If the last component ofsrcPathis 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 thefileManager:shouldCopyItemAtPath:toPath:method instead. If the delegate method returnsYEStrue, 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’sfileManager:shouldProceedAfterError:copyingItemAtURL:toURL:orfileManager:shouldProceedAfterError:copyingItemAtPath:toPath:method to determine how to proceed.Availability
Available in OS X v10.5 and later.
-
Moves the file or directory at the specified URL to a new location synchronously.
Declaration
Parameters
srcURLThe 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.dstURLThe 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 benil.errorOn 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
YEStrueif the item was moved successfully or the file manager’s delegate stopped the operation deliberately. ReturnsNOfalseif an error occurred.Discussion
When moving items, the current process must have permission to read the item at
srcURLand write the parent directory ofdstURL. If the item atsrcURLis 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 atdstURL, this method stops the move attempt and returns an appropriate error. If the last component ofsrcURLis 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 thefileManager: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 returnsYEStrue, 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’sfileManager:shouldProceedAfterError:movingItemAtURL:toURL:orfileManager: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.
-
Moves the file or directory at the specified path to a new location synchronously.
Declaration
Parameters
srcPathThe path to the file or directory you want to move. This parameter must not be
nil.dstPathThe 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 benil.errorOn 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
YEStrueif the item was moved successfully or the file manager’s delegate stopped the operation deliberately. ReturnsNOfalseif an error occurred.Discussion
When moving items, the current process must have permission to read the item at
srcPathand write the parent directory ofdstPath. If the item atsrcPathis 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 atdstPath, this method stops the move attempt and returns an appropriate error. If the last component ofsrcPathis 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 thefileManager: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 returnsYEStrue, 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’sfileManager:shouldProceedAfterError:movingItemAtURL:toURL:orfileManager: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.
-
An opaque token that represents the current user’s iCloud identity (read-only)
Declaration
Swift
@NSCopying var ubiquityIdentityToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? { get }Objective-C
@property(readonly, copy) id<NSObject, NSCopying, NSCoding> ubiquityIdentityTokenDiscussion
When iCloud is currently available, this property contains an opaque object representing the identity of the current user. If iCloud is unavailable for any reason or there is no logged-in user, the value of this property is
nil. Accessing the value of this property is relatively fast so you can check the value at launch time from your app’s main thread.You can use the token in this property, together with the
NSUbiquityIdentityDidChangeNotificationnotification, 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 identity token changes and the system posts the notification. If you stored or archived the previous token, compare that token to the newly obtained one using theisEqual:method to determine if the users are the same or different.Accessing the token in this property does not connect your app to its ubiquity containers. To establish access to a ubiquity container, call the
URLForUbiquityContainerIdentifier:method. In OS X, you can instead use anNSDocumentobject, which establishes access automatically.Availability
Available in OS X v10.8 and later.
See Also
-
Returns the URL for the iCloud container associated with the specified identifier and establishes access to that container.
Declaration
Parameters
containerIDThe fully-qualified container identifier for an iCloud container directory. 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> is 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
nilfor 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
nilif 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-identifiersentitlement 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.
-
Returns a Boolean indicating whether the item is targeted for storage in iCloud.
Declaration
Objective-C
- (BOOL)isUbiquitousItemAtURL:(NSURL *)urlParameters
urlSpecify the URL for the file or directory whose status you want to check.
Return Value
YEStrueif the item is targeted for iCloud storage orNOfalseif it is not. This method also returnsNOfalseif no item exists aturl.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 ofYEStruefor itsflagparameter. This method does not reflect whether the file has actually been uploaded to any iCloud servers. To determine a file’s upload status, check theNSURLUbiquitousItemIsUploadedKeyattribute of the correspondingNSURLobject.Availability
Available in OS X v10.7 and later.
-
Sets whether the item at the specified URL should be stored in the cloud.
Declaration
Parameters
flagSpecify
YEStrueto move the item to iCloud orNOfalseto remove it from iCloud (if it is there currently).urlSpecify the URL of the item (file or directory) that you want to store in iCloud.
destinationURLMoving a file into iCloud 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.Moving a file out of iCloud Specify the location on the local device.
errorOutOn 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 specifynilto ignore the error information.Return Value
YEStrueif the item’s status was updated successfully orNOfalseif an error occurred. If this method returnsNOfalseand you specified a value for theerrorOutparameter, 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.
If your app is presenting the file’s contents to the user, it must have an active file presenter object configured to monitor the specified file or directory before calling this method. When you specify
YEStruefor theflagparameter, this method attempts to move the file or directory to the cloud and returnsYEStrueif it is successful. Calling 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.
-
Starts downloading (if necessary) the specified item to the local system.
Declaration
Swift
func startDownloadingUbiquitousItemAtURL(_url: NSURL) throwsParameters
urlSpecify the URL for the file or directory in the cloud that you want to download.
errorOutOn 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 specifynilto ignore the error information.Return Value
YEStrueif the download started successfully or was not necessary, otherwiseNOfalse. IfNOfalseis returned anderrorOutis notnil, anNSErrorobject 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
NSMetadataUbiquitousItemDownloadingStatusKeykey. You can also use related keys to determine the current progress in downloading the file.Availability
Available in OS X v10.7 and later.
-
Removes the local copy of the specified cloud-based item.
Declaration
Swift
func evictUbiquitousItemAtURL(_url: NSURL) throwsParameters
urlSpecify the URL to a file or directory in iCloud storage.
errorOutOn 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 specifynilto ignore the error information.Return Value
YEStrueif the local item was removed successfully or NO if it was not. IfNOfalseis returned anderrorOutis notnil, anNSErrorobject describing the error is returned in that parameter.Discussion
Do not use a coordinated write to perform this operation. On OS X v10.7 or earlier, the framework takes a coordinated write in its implementation of this method, so taking one in your app causes a deadlock. On OS X v10.8 and later, the framework detects coordination done by your app on the same thread as the call to this method, to avoid deadlocking.
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
NSFileManagerroutines 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.
-
URLForPublishingUbiquitousItemAtURL(_:expirationDate:) - URLForPublishingUbiquitousItemAtURL:expirationDate:error:Returns a URL that can be emailed to users to allow them to download a copy of a cloud-based flat file item.
Declaration
Swift
func URLForPublishingUbiquitousItemAtURL(_url: NSURL, expirationDateoutDate: AutoreleasingUnsafeMutablePointer<NSDate?>) throws -> NSURLParameters
urlSpecify 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. The file must be a flat file, not a bundle. The file at the specified URL must already be uploaded to iCloud when you call this method.outDateOn 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.errorOn 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. Returnsnilif the URL could not be created for any reason.Discussion
This method creates a snapshot of the specified flat 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
outDateparameter, after which it is automatically deleted. Explicitly deleting the item by calling theremoveItemAtURL:error:orremoveItemAtPath:error:method also deletes all old versions of the item, invalidating URLs to those versions returned by this method.Your app must have access to the network for this call to succeed. If the specified file is in the process of being uploaded to iCloud, you must not call this method until the upload has finished.
Availability
Available in OS X v10.7 and later.
See Also
-
Creates a symbolic link at the specified URL that points to an item at the given URL.
Declaration
Parameters
urlThe file URL at which to create the new symbolic link. The last path component of the URL issued as the name of the link.
destURLThe file URL that contains the item to be pointed to by the link. In other words, this is the destination of the link.
errorOn 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
YEStrueif the symbolic link was created orNOfalseif an error occurred. This method also returnsNOfalseif a file, directory, or link already exists aturl.Discussion
This method does not traverse symbolic links contained in
destURL, making it possible to create symbolic links to locations that do not yet exist. Also, if the final path component inurlis a symbolic link, that link is not followed.Availability
Available in OS X v10.7 and later.
-
createSymbolicLinkAtPath(_:withDestinationPath:) - createSymbolicLinkAtPath:withDestinationPath:error:Creates a symbolic link that points to the specified destination.
Declaration
Parameters
pathThe path at which to create the new symbolic link. The last path component is used as the name of the link.
destPathThe path that contains the item to be pointed to by the link. In other words, this is the destination of the link.
errorIf an error occurs, upon return contains an
NSErrorobject that describes the problem. PassNULLif you do not want error information.Return Value
YEStrueif the symbolic link was created orNOfalseif an error occurred. This method also returnsNOfalseif a file, directory, or link already exists atpath.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 inpathis a symbolic link, that link is not followed.Availability
Available in OS X v10.5 and later.
-
Creates a hard link between the items at the specified URLs.
Declaration
Parameters
srcURLThe 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.dstURLThe 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.errorOn 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
YEStrueif the hard link was created orNOfalseif an error occurred. This method also returnsNOfalseif a file, directory, or link already exists atdstURL.Discussion
Use this method to create hard links between files in the current file system. If
srcURLis a directory, this method creates a new directory atdstURLand then creates hard links for the items in that directory. IfsrcURLis (or contains) a symbolic link, the symbolic link is copied and not converted to a hard link atdstURL.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 thefileManager:shouldLinkItemAtPath:toPath:method instead. If the delegate method returnsYEStrue, or if the delegate does not implement the appropriate methods, the file manager creates the hard link. If there is an error linking one out of several items, the file manager may also call the delegate’sfileManager:shouldProceedAfterError:linkingItemAtURL:toURL:orfileManager:shouldProceedAfterError:linkingItemAtPath:toPath:method to determine how to proceed.Availability
Available in OS X v10.6 and later.
-
Creates a hard link between the items at the specified paths.
Declaration
Parameters
srcPathThe path that specifies the item you wish to link to. The value in this parameter must not be
nil.dstPathThe path that identifies the location where the link will be created. The value in this parameter must not be
nil.errorOn 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
YEStrueif the hard link was created orNOfalseif an error occurred. This method also returnsNOfalseif a file, directory, or link already exists atdstPath.Discussion
Use this method to create hard links between files in the current file system. If
srcPathis a directory, this method creates a new directory atdstPathand then creates hard links for the items in that directory. IfsrcPathis (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 thefileManager:shouldLinkItemAtPath:toPath:method instead. If the delegate method returnsYEStrue, or if the delegate does not implement the appropriate methods, the file manager creates the hard link. If there is an error linking one out of several items, the file manager may also call the delegate’sfileManager:shouldProceedAfterError:linkingItemAtURL:toURL:orfileManager:shouldProceedAfterError:linkingItemAtPath:toPath:method to determine how to proceed.Availability
Available in OS X v10.5 and later.
-
Returns the path of the item pointed to by a symbolic link.
Declaration
Parameters
pathThe path of a file or directory.
errorIf an error occurs, upon return contains an
NSErrorobject that describes the problem. PassNULLif you do not want error information.Return Value
An
NSStringobject containing the path of the directory or file to which the symbolic linkpathrefers, ornilupon failure. If the symbolic link is specified as a relative path, that relative path is returned.Discussion
Availability
Available in OS X v10.5 and later.
-
Returns a Boolean value that indicates whether a file or directory exists at a specified path.
Declaration
Objective-C
- (BOOL)fileExistsAtPath:(NSString *)pathParameters
pathThe path of the file or directory. If
pathbegins with a tilde (~), it must first be expanded withstringByExpandingTildeInPath; otherwise, this method returnsNOfalse.App Sandbox does not restrict which path values may be passed to this parameter.
Return Value
YEStrueif a file at the specified path exists, orNOfalseif the file does not exist or its existence could not be determined.Discussion
If the file at
pathis inaccessible to your app, perhaps because one or more parent directories are inaccessible, this method returnsNOfalse. If the final element inpathspecifies a symbolic link, this method traverses the link and returnsYEStrueorNOfalsebased on the existence of the file at the link destination.Availability
Available in OS X v10.0 and later.
-
Returns a Boolean value that indicates whether a file or directory exists at a specified path. The
isDirectoryout parameter indicates whether the path points to a directory or a regular file.Declaration
Swift
func fileExistsAtPath(_path: String, isDirectoryisDirectory: UnsafeMutablePointer<ObjCBool>) -> BoolObjective-C
- (BOOL)fileExistsAtPath:(NSString *)pathisDirectory:(BOOL *)isDirectoryParameters
pathThe path of a file or directory. If
pathbegins with a tilde (~), it must first be expanded withstringByExpandingTildeInPath, or this method will returnNOfalse.isDirectoryUpon return, contains
YEStrueifpathis a directory or if the final path element is a symbolic link that points to a directory; otherwise, containsNOfalse. Ifpathdoesn’t exist, this value is undefined upon return. PassNULLif you do not need this information.Return Value
YEStrueif a file at the specified path exists, orNOfalseif the file’s does not exist or its existence could not be determined.Discussion
If the file at
pathis inaccessible to your app, perhaps because one or more parent directories are inaccessible, this method returnsNOfalse. If the final element inpathspecifies a symbolic link, this method traverses the link and returnsYEStrueorNOfalsebased on the existence of the file at the link destination.If you need to further determine whether
pathis a package, use theisFilePackageAtPath:method ofNSWorkspace.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];// ...
Availability
Available in OS X v10.0 and later.
-
Returns a Boolean value that indicates whether the invoking object appears able to read a specified file.
Declaration
Objective-C
- (BOOL)isReadableFileAtPath:(NSString *)pathParameters
pathA file path.
Return Value
YEStrueif the current process has read privileges for the file atpath; otherwiseNOfalseif the process does not have read privileges or the existence of the file could not be determined.Discussion
If the file at
pathis inaccessible to your app, perhaps because it does not have search privileges for one or more parent directories, this method returnsNOfalse. 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.
-
Returns a Boolean value that indicates whether the invoking object appears able to write to a specified file.
Declaration
Objective-C
- (BOOL)isWritableFileAtPath:(NSString *)pathParameters
pathA file path.
Return Value
YEStrueif the current process has write privileges for the file atpath; otherwiseNOfalseif the process does not have write privileges or the existence of the file could not be determined.Discussion
If the file at
pathis inaccessible to your app, perhaps because it does not have search privileges for one or more parent directories, this method returnsNOfalse. 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.
-
Returns a Boolean value that indicates whether the operating system appears able to execute a specified file.
Declaration
Objective-C
- (BOOL)isExecutableFileAtPath:(NSString *)pathParameters
pathA file path.
Return Value
YEStrueif the current process has execute privileges for the file atpath; otherwiseNOfalseif the process does not have execute privileges or the existence of the file could not be determined.Discussion
If the file at
pathis inaccessible to your app, perhaps because it does not have search privileges for one or more parent directories, this method returnsNOfalse. 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.
-
Returns a Boolean value that indicates whether the invoking object appears able to delete a specified file.
Declaration
Objective-C
- (BOOL)isDeletableFileAtPath:(NSString *)pathParameters
pathA file path.
Return Value
YEStrueif the current process has delete privileges for the file atpath; otherwiseNOfalseif 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
pathor it must have the same owner as the item atpath. Ifpathis a directory, every item contained inpathmust be deletable by the current process.If the file at
pathis inaccessible to your app, perhaps because it does not have search privileges for one or more parent directories, this method returnsNOfalse. If the item atpathis a symbolic link, it is not traversed.Availability
Available in OS X v10.0 and later.
-
Returns an array of strings representing the user-visible components of a given path.
Declaration
Parameters
pathA pathname.
Return Value
An array of
NSStringobjects representing the user-visible (for the Finder, Open and Save panels, and so on) components ofpath. Returnsnilif 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.
-
Returns the display name of the file or directory at a specified path.
Declaration
Parameters
pathThe path of a file or directory.
Return Value
The name of the file or directory at
pathin a localized form appropriate for presentation to the user. If there is no file or directory atpath, or if an error occurs, returnspathas 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èqueand not the nameLibrary, 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);}
Availability
Available in OS X v10.1 and later.
-
Returns the attributes of the item at a given path.
Declaration
Objective-C
- (NSDictionary<NSString *,id> *)attributesOfItemAtPath:(NSString *)patherror:(NSError * _Nullable *)errorParameters
pathThe path of a file or directory.
errorOn 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
NSDictionaryobject that describes the attributes (file, directory, symlink, and so on) of the file specified bypath, ornilif an error occurred. The keys in the dictionary are described inFile Attribute Keys.Discussion
Special Considerations
If the item at the path is a symbolic link—that is, the value of the
NSFileTypekey in the attributes dictionary isNSFileTypeSymbolicLink—you can use thedestinationOfSymbolicLinkAtPath:error:method to retrieve the path of the item pointed to by the link. You can also use thestringByResolvingSymlinksInPathmethod ofNSStringto resolve links in the path before retrieving the item’s attributes.As a convenience,
NSDictionaryprovides a set of methods (declared as a category onNSDictionary) for quickly and efficiently obtaining attribute information from the returned dictionary:fileGroupOwnerAccountName,fileModificationDate,fileOwnerAccountName,filePosixPermissions,fileSize,fileSystemFileNumber,fileSystemNumber, andfileType.Availability
Available in OS X v10.5 and later.
See Also
-
Returns a dictionary that describes the attributes of the mounted file system on which a given path resides.
Declaration
Objective-C
- (NSDictionary<NSString *,id> *)attributesOfFileSystemForPath:(NSString *)patherror:(NSError * _Nullable *)errorParameters
pathAny pathname within the mounted file system.
errorOn 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
NSDictionaryobject that describes the attributes of the mounted file system on whichpathresides. 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.
-
Sets the attributes of the specified file or directory.
Declaration
Objective-C
- (BOOL)setAttributes:(NSDictionary<NSString *,id> *)attributesofItemAtPath:(NSString *)patherror:(NSError * _Nullable *)errorParameters
attributesA dictionary containing as keys the attributes to set for
pathand 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.pathThe path of a file or directory.
errorOn 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
YEStrueif all changes succeed. If any change fails, returnsNOfalse, 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
NSFilePosixPermissionsvalue must be initialized with the code representing the POSIX file-permissions bit pattern.NSFileHFSCreatorCodeandNSFileHFSTypeCodewill only be heeded whenpathspecifies a file.Availability
Available in OS X v10.5 and later.
See Also
-
Returns the contents of the file at the specified path.
Declaration
Parameters
pathThe path of the file whose contents you want.
Return Value
An
NSDataobject with the contents of the file. Ifpathspecifies a directory, or if some other error occurs, this method returnsnil.Availability
Available in OS X v10.0 and later.
-
Returns a Boolean value that indicates whether the files or directories in specified paths have the same contents.
Declaration
Parameters
path1The path of a file or directory to compare with the contents of
path2.path2The path of a file or directory to compare with the contents of
path1.Return Value
YEStrueif file or directory specified inpath1has the same contents as that specified inpath2, otherwiseNOfalse.Discussion
If
path1andpath2are 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
-
getRelationship(_:ofDirectoryAtURL:toItemAtURL:) - getRelationship:ofDirectoryAtURL:toItemAtURL:error:Determines the type of relationship that exists between a directory and item.
Declaration
Swift
func getRelationship(_outRelationship: UnsafeMutablePointer<NSURLRelationship>, ofDirectoryAtURLdirectoryURL: NSURL, toItemAtURLotherURL: NSURL) throwsObjective-C
- (BOOL)getRelationship:(NSURLRelationship *)outRelationshipofDirectoryAtURL:(NSURL *)directoryURLtoItemAtURL:(NSURL *)otherURLerror:(NSError * _Nullable *)errorParameters
outRelationshipA pointer to a variable in which to put the relationship between
directoryURLandotherURL. For a list of possible values, seeNSURLRelationship.directoryURLThe URL of the directory that potentially contains the item in
otherURL. The URL in this parameter must specify a directory. This parameter must not benil.otherURLThe URL of the file or directory whose relationship to
directoryURLis being tested. This parameter must not benil.errorOn 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
YEStrueif the relationship between the items was successfully determined, orNOfalseif an error occurred.Discussion
Use this method to determine the relationship between an item and a directory whose location you already know. If the relationship between the items is determined successfully, this method sets the value of the
outRelationshipparameter to an appropriate value and returnsYEStrue. The directory may contain the item, it may be the same as the item, or it may not have a direct relationship to the item.Availability
Available in OS X v10.10 and later.
-
getRelationship(_:ofDirectory:inDomain:toItemAtURL:) - getRelationship:ofDirectory:inDomain:toItemAtURL:error:Determines the type of relationship that exists between a system directory and the specified item.
Declaration
Swift
func getRelationship(_outRelationship: UnsafeMutablePointer<NSURLRelationship>, ofDirectorydirectory: NSSearchPathDirectory, inDomaindomainMask: NSSearchPathDomainMask, toItemAtURLurl: NSURL) throwsObjective-C
- (BOOL)getRelationship:(NSURLRelationship *)outRelationshipofDirectory:(NSSearchPathDirectory)directoryinDomain:(NSSearchPathDomainMask)domainMasktoItemAtURL:(NSURL *)urlerror:(NSError * _Nullable *)errorParameters
outRelationshipA pointer to a variable in which to put the relationship between
directoryURLandotherURL. For a list of possible values, seeNSURLRelationship.directoryThe search path directory. For a list of possible values, see
NSSearchPathDirectory.domainMaskThe file system domain to search. Specify
0for this parameter if you want the file manager to choose the domain that is most appropriate for the specifiedurl.urlThe URL of the file or directory whose relationship to
directoryURLis being tested. This parameter must not benil.errorOn 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
YEStrueif the relationship between the items was successfully determined, orNOfalseif an error occurred.Discussion
Use this method to determine the relationship between an item and one of the system-specific directories. For example, you might use this method to determine if the specified item is in the user’s
Documentsdirectory or is in the trash. If the relationship between the items is determined successfully, this method sets the value of theoutRelationshipparameter to an appropriate value and returnsYEStrue. The directory may contain the item, it may be the same as the item, or it may not have a direct relationship to the item.Availability
Available in OS X v10.10 and later.
-
Returns a C-string representation of a given path that properly encodes Unicode strings for use by the file system.
Declaration
Swift
func fileSystemRepresentationWithPath(_path: String) -> UnsafePointer<Int8>Objective-C
- (const char *)fileSystemRepresentationWithPath:(NSString *)pathParameters
pathA 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
paththat 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
pathisnilor 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.
-
Returns an
NSStringobject whose contents are derived from the specified C-string path.Declaration
Swift
func stringWithFileSystemRepresentation(_str: UnsafePointer<Int8>, lengthlen: Int) -> StringObjective-C
- (NSString *)stringWithFileSystemRepresentation:(const char *)stringlength:(NSUInteger)lenParameters
stringA C string representation of a pathname.
lenThe number of characters in
string.Return Value
An
NSStringobject converted from the C-string representationstringwith lengthlenof 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
-
The delegate of the file manager object.
Declaration
Swift
unowned(unsafe) var delegate: NSFileManagerDelegate?Objective-C
@property(assign) id< NSFileManagerDelegate > delegateDiscussion
It is recommended that you assign a delegate to the file manager object only if you allocated and initialized the object yourself. Avoid assigning a delegate to the shared file manager obtained from the
defaultManagermethod.The default value of this property is
nil. When assigning a delegate to this property, your object must conform to theNSFileManagerDelegateprotocol.Availability
Available in OS X v10.5 and later.
-
Changes the path of the current working directory to the specified path.
Declaration
Objective-C
- (BOOL)changeCurrentDirectoryPath:(NSString *)pathParameters
pathThe path of the directory to which to change.
Return Value
YEStrueif successful, otherwiseNOfalse.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.
-
currentDirectoryPath currentDirectoryPathPropertyThe path to the program’s current directory. (read-only)
Declaration
Swift
var currentDirectoryPath: String { get }Objective-C
@property(readonly, copy) NSString *currentDirectoryPathDiscussion
The current directory path is the starting point for any relative paths you specify. For example, if the current directory is
/tmpand you specify a relative pathname ofreports/info.txt, the resulting full path for the item is/tmp/reports/info.txt.When an app is launched, this property is initially set to the app’s current working directory. If the current working directory is not accessible for any reason, the value of this property is
nil. You can change the value of this property by calling thechangeCurrentDirectoryPath:method.Availability
Available in OS X v10.0 and later.
-
- copyPath:toPath:handler:(OS X v10.5)Copies the directory or file specified in a given path to a different location in the file system identified by another path.
Deprecation Statement
Use
copyItemAtURL:toURL:error:instead.Declaration
Parameters
sourceThe location of the source file.
destinationThe location to which to copy the file specified by
source.handlerAn object that responds to the callback messages
fileManager:willProcessPath:andfileManager:shouldProceedAfterError:. You can specifynilforhandler; if you do so and an error occurs, the method automatically returnsNOfalse.Return Value
YEStrueif the copy operation is successful. If the operation is not successful, but the callback handler offileManager:shouldProceedAfterError:returnsYEStrue,copyPath:toPath:handler:also returnsYEStrue. Otherwise this method returnsNOfalse. The method also attempts to make the attributes of the directory or file atdestinationidentical tosource, but ignores any failure at this attempt.Discussion
If
sourceis a file, the method creates a file atdestinationthat holds the exact contents of the original file (this includes BSD special files). Ifsourceis a directory, the method creates a new directory atdestinationand recursively populates it with duplicates of the files and directories contained insource, preserving all links. The file specified insourcemust exist, whiledestinationmust 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.The handler callback mechanism is similar to delegation.
NSFileManagersendsfileManager:willProcessPath:when it begins a copy, move, remove, or link operation. It sendsfileManager:shouldProceedAfterError:when it encounters any error in processing.Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
moveItemAtPath:toPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- movePath:toPath:handler:(OS X v10.5)Moves the directory or file specified by a given path to a different location in the file system identified by another path.
Deprecation Statement
Use
moveItemAtURL:toURL:error:instead.Declaration
Parameters
sourceThe path of a file or directory to move.
sourcemust exist.destinationThe path to which
sourceis moved.destinationmust not yet exist. The destination path must end in a filename; there is no implicit adoption of the source filename.handlerAn object that responds to the callback messages
fileManager:willProcessPath:andfileManager:shouldProceedAfterError:. You can specifynilforhandler; if you do so and an error occurs, the method automatically returnsNOfalse.Return Value
YEStrueif the move operation is successful. If the operation is not successful, but the handler methodfileManager:shouldProceedAfterError:returnsYEStrue,movePath:toPath:handler:also returnsYEStrue; otherwise returnsNOfalse.Discussion
If
sourceis a file, the method creates a file atdestinationthat holds the exact contents of the original file and then deletes the original file. Ifsourceis a directory,movePath:toPath:handler:creates a new directory atdestinationand recursively populates it with duplicates of the files and directories contained insource. It then deletes the old directory and its contents. Symbolic links are not traversed, however links are preserved. File or directory attributes—that is, metadata such as owner and group numbers, file permissions, and modification date—are also moved.The handler callback mechanism is similar to delegation.
NSFileManagersendsfileManager:willProcessPath:when it begins a copy, move, remove, or link operation. It sendsfileManager:shouldProceedAfterError:when it encounters any error in processing.If a failure in a move operation occurs, either the preexisting path or the new path remains intact, but not both.
Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
copyItemAtPath:toPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- removeFileAtPath:handler:(OS X v10.5)Deletes the file, link, or directory (including, recursively, all subdirectories, files, and links in the directory) identified by a given path.
Deprecation Statement
Use
removeItemAtURL:error:instead.Declaration
Objective-C
- (BOOL)removeFileAtPath:(NSString *)pathhandler:(id)handlerParameters
pathThe path of a file, link, or directory to delete. The value must not be "
." or "..".handlerAn object that responds to the callback messages
fileManager:willProcessPath:andfileManager:shouldProceedAfterError:. You can specifynilforhandler; if you do so and an error occurs, the deletion stops and the method automatically returnsNOfalse.Return Value
YEStrueif the removal operation is successful. If the operation is not successful, but the handler methodfileManager:shouldProceedAfterError:returnsYEStrue, also returnsYEStrue; otherwise returnsNOfalse.Discussion
This callback mechanism provided by
handleris similar to delegation.NSFileManagersendsfileManager:willProcessPath:when it begins a copy, move, remove, or link operation. It sendsfileManager:shouldProceedAfterError:when it encounters any error in processing.Since the removal of directory contents is so thorough and final, be careful when using this method. If you specify "
." or ".." forpathanNSInvalidArgumentExceptionexception is raised. This method does not traverse symbolic links.Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
removeItemAtURL:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- changeFileAttributes:atPath:(OS X v10.5)Changes the attributes of a given file or directory.
Deprecation Statement
Use
setAttributes:ofItemAtPath:error:instead.Declaration
Objective-C
- (BOOL)changeFileAttributes:(NSDictionary *)attributesatPath:(NSString *)pathParameters
attributesA dictionary containing as keys the attributes to set for
pathand as values the corresponding value for the attribute. You can set following: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.For the
NSFilePosixPermissionsvalue, specify a file mode from the OR’d permission bit masks defined insys/stat.h. See the man page for thechmodfunction (man 2 chmod) for an explanation.pathA path to a file or directory.
Return Value
YEStrueif all changes succeed. If any change fails, returnsNOfalse, 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.
The
NSFilePosixPermissionsvalue must be initialized with the code representing the POSIX file-permissions bit pattern.NSFileHFSCreatorCodeandNSFileHFSTypeCodewill only be heeded whenpathspecifies a file.Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
setAttributes:ofItemAtPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- fileAttributesAtPath:traverseLink:(OS X v10.5)Returns a dictionary that describes the POSIX attributes of the file specified at a given.
Deprecation Statement
Use
attributesOfItemAtPath:error:instead.Declaration
Objective-C
- (NSDictionary *)fileAttributesAtPath:(NSString *)pathtraverseLink:(BOOL)flagParameters
pathA file path.
flagIf
pathis not a symbolic link, this parameter has no effect. Ifpathis a symbolic link, then:If
YEStruethe attributes of the linked-to file are returned, or if the link points to a nonexistent file the method returnsnil.If
NOfalse, the attributes of the symbolic link are returned.
Return Value
An
NSDictionaryobject that describes the POSIX attributes of the file specified atpath. The keys in the dictionary are described inFile Attribute Keys. If there is no item atpath, returnsnil.Discussion
This code example gets several attributes of a file and logs them.
NSFileManager *fileManager = [[NSFileManager alloc] init];NSString *path = @"/tmp/List";NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:path traverseLink:YES];if (fileAttributes != nil) {NSNumber *fileSize;NSString *fileOwner;NSDate *fileModDate;if (fileSize = [fileAttributes objectForKey:NSFileSize]) {NSLog(@"File size: %qi\n", [fileSize unsignedLongLongValue]);}if (fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName]) {NSLog(@"Owner: %@\n", fileOwner);}if (fileModDate = [fileAttributes objectForKey:NSFileModificationDate]) {NSLog(@"Modification date: %@\n", fileModDate);}}else {NSLog(@"Path (%@) is invalid.", path);}
As a convenience,
NSDictionaryprovides a set of methods (declared as a category inNSFileManager.h) for quickly and efficiently obtaining attribute information from the returned dictionary:fileGroupOwnerAccountName,fileModificationDate,fileOwnerAccountName,filePosixPermissions,fileSize,fileSystemFileNumber,fileSystemNumber, andfileType. For example, you could rewrite the file modification statement in the code example above as:if (fileModDate = [fileAttributes fileModificationDate])NSLog(@"Modification date: %@\n", fileModDate);
Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
attributesOfItemAtPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- fileSystemAttributesAtPath:(OS X v10.5)Returns a dictionary that describes the attributes of the mounted file system on which a given path resides.
Deprecation Statement
Use
attributesOfFileSystemForPath:error:instead.Declaration
Objective-C
- (NSDictionary *)fileSystemAttributesAtPath:(NSString *)pathParameters
pathAny pathname within the mounted file system.
Return Value
An
NSDictionaryobject that describes the attributes of the mounted file system on whichpathresides. See File-System Attribute Keys for a description of the keys available in the dictionary.Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
attributesOfFileSystemForPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- directoryContentsAtPath:(OS X v10.5)Returns the directories and files (including symbolic links) contained in a given directory.
Deprecation Statement
Use
contentsOfDirectoryAtPath:error:instead.Parameters
pathA path to a directory.
Return Value
An array of
NSStringobjects identifying the directories and files (including symbolic links) contained inpath. Returns an empty array if the directory exists but has no contents. Returnsnilif the directory specified atpathdoes 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 and does not traverse symbolic links in the specified directory. This returned array does not contain strings for the current directory (“
.”), parent directory (“..”), or resource forks (begin with “._”).Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
contentsOfDirectoryAtPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- createDirectoryAtPath:attributes:(OS X v10.5)Creates a directory (without contents) at a given path with given attributes.
Deprecation Statement
Use
createDirectoryAtURL:withIntermediateDirectories:attributes:error:instead.Declaration
Objective-C
- (BOOL)createDirectoryAtPath:(NSString *)pathattributes:(NSDictionary *)attributesParameters
pathThe path at which to create the new directory. The directory to be created must not yet exist, but its parent directory must exist.
attributesThe file attributes for the new directory. The attributes you can set are owner and group numbers, file permissions, and modification date. If you specify
nilforattributes, default values for these attributes are set (particularly write access for the creator and read access for others). The Constants section lists the global constants used as keys in theattributesdictionary. Some of the keys, such asNSFileHFSCreatorCodeandNSFileHFSTypeCode, do not apply to directories.Return Value
YEStrueif the operation was successful, otherwiseNOfalse.Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
createDirectoryAtPath:withIntermediateDirectories:attributes:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- createSymbolicLinkAtPath:pathContent:(OS X v10.5)Creates a symbolic link identified by a given path that refers to a given location.
Deprecation Statement
Use
createSymbolicLinkAtURL:withDestinationURL:error:instead.Declaration
Parameters
pathThe path for a symbolic link.
otherPathThe path to which
pathshould refer.Return Value
YEStrueif the operation is successful, otherwiseNOfalse. ReturnsNOfalseif a file, directory, or symbolic link identical topathalready exists.Discussion
Creates a symbolic link identified by
paththat refers to the locationotherPathin the file system.Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
createSymbolicLinkAtPath:withDestinationPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- pathContentOfSymbolicLinkAtPath:(OS X v10.5)Returns the path of the directory or file that a symbolic link at a given path refers to.
Deprecation Statement
Use
destinationOfSymbolicLinkAtPath:error:instead.Parameters
pathThe path of a symbolic link.
Return Value
The path of the directory or file to which the symbolic link
pathrefers, ornilupon failure. If the symbolic link is specified as a relative path, that relative path is returned.Special Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
destinationOfSymbolicLinkAtPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
- linkPath:toPath:handler:(OS X v10.5)Creates a link from a source to a destination.
Deprecation Statement
Use
linkItemAtURL:toURL:error:instead.Declaration
Parameters
sourceA path that identifies a source file or directory.
The file, link, or directory specified by
sourcemust exist.destinationA path that identifies a destination file or directory.
The destination should not yet exist. The destination path must end in a filename; there is no implicit adoption of the source filename.
handlerAn object that responds to the callback messages
fileManager:willProcessPath:andfileManager:shouldProceedAfterError:. You can specifynilforhandler; if you do so and an error occurs, the method automatically returnsNOfalse.Return Value
YEStrueif the link operation is successful. If the operation is not successful, but the handler methodfileManager:shouldProceedAfterError:returnsYEStrue, also returnsYEStrue. Otherwise returnsNOfalse.Discussion
The handler callback mechanism is similar to delegation.
NSFileManagersendsfileManager:willProcessPath:when it begins a copy, move, remove, or link operation. It sendsfileManager:shouldProceedAfterError:when it encounters any error in processingSpecial Considerations
Because this method does not return error information, it has been deprecated as of OS X v10.5. Use
removeItemAtPath:error:instead.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
fileManager:shouldProceedAfterError:(OS X v10.5)An
NSFileManagerobject sends this message to its handler for each error it encounters when copying, moving, removing, or linking files or directories.Deprecation Statement
See delegate methods for copy, move, remove, and link methods.
Declaration
Objective-C
- (BOOL)fileManager:(NSFileManager *)managershouldProceedAfterError:(NSDictionary *)errorInfoDiscussion
An
NSFileManagerobject,manager, sends this message for each error it encounters when copying, moving, removing, or linking files or directories. The return value is passed back to the invoker ofcopyPath:toPath:handler:,movePath:toPath:handler:,removeFileAtPath:handler:, orlinkPath:toPath:handler:. If an error occurs and your handler has not implemented this method, the invoking method automatically returnsNOfalse.Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
See Also
-
fileManager:willProcessPath:(OS X v10.5)An
NSFileManagerobject sends this message to a handler immediately before attempting to move, copy, rename, or delete, or before attempting to link to a given path.Deprecation Statement
See delegate methods for copy, move, link, and remove methods.
Declaration
Objective-C
- (void)fileManager:(NSFileManager *)managerwillProcessPath:(NSString *)pathDiscussion
You can implement this method in your handler to monitor file operations.
Availability
Available in OS X v10.0 and later.
Deprecated in OS X v10.5.
-
Options for enumerating mounted volumes with the
mountedVolumeURLsIncludingResourceValuesForKeys:options:method.Declaration
Swift
struct NSVolumeEnumerationOptions : OptionSetType { init(rawValuerawValue: UInt) static var SkipHiddenVolumes: NSVolumeEnumerationOptions { get } static var ProduceFileReferenceURLs: NSVolumeEnumerationOptions { get } }Objective-C
typedef enum : NSUInteger { NSVolumeEnumerationSkipHiddenVolumes = 1L << 1, NSVolumeEnumerationProduceFileReferenceURLs = 1L << 2 } NSVolumeEnumerationOptions;Constants
-
SkipHiddenVolumesNSVolumeEnumerationSkipHiddenVolumesThe enumeration skips hidden volumes.
Available in OS X v10.6 and later.
-
ProduceFileReferenceURLsNSVolumeEnumerationProduceFileReferenceURLsThe enumeration produces file reference URLs rather than path-based URLs.
Available in OS X v10.6 and later.
Import Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.6 and later.
-
-
Options for enumerating the contents of directories with the
contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:method.Declaration
Swift
struct NSDirectoryEnumerationOptions : OptionSetType { init(rawValuerawValue: UInt) static var SkipsSubdirectoryDescendants: NSDirectoryEnumerationOptions { get } static var SkipsPackageDescendants: NSDirectoryEnumerationOptions { get } static var SkipsHiddenFiles: NSDirectoryEnumerationOptions { get } }Objective-C
typedef enum : NSUInteger { NSDirectoryEnumerationSkipsSubdirectoryDescendants = 1L << 0, NSDirectoryEnumerationSkipsPackageDescendants = 1L << 1, NSDirectoryEnumerationSkipsHiddenFiles = 1L << 2 } NSDirectoryEnumerationOptions;Constants
-
SkipsSubdirectoryDescendantsNSDirectoryEnumerationSkipsSubdirectoryDescendantsPerform a shallow enumeration; do not descend into directories.
Available in OS X v10.6 and later.
-
SkipsPackageDescendantsNSDirectoryEnumerationSkipsPackageDescendantsDo not descend into packages.
Available in OS X v10.6 and later.
-
SkipsHiddenFilesNSDirectoryEnumerationSkipsHiddenFilesDo not enumerate hidden files.
Available in OS X v10.6 and later.
Import Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.6 and later.
-
-
The constants specify the replacement behavior in
replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:.Declaration
Swift
struct NSFileManagerItemReplacementOptions : OptionSetType { init(rawValuerawValue: UInt) static var UsingNewMetadataOnly: NSFileManagerItemReplacementOptions { get } static var WithoutDeletingBackupItem: NSFileManagerItemReplacementOptions { get } }Objective-C
typedef enum : NSUInteger { NSFileManagerItemReplacementUsingNewMetadataOnly = 1UL << 0, NSFileManagerItemReplacementWithoutDeletingBackupItem = 1UL << 1 } NSFileManagerItemReplacementOptions;Constants
-
UsingNewMetadataOnlyNSFileManagerItemReplacementUsingNewMetadataOnlyCauses
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.
-
WithoutDeletingBackupItemNSFileManagerItemReplacementWithoutDeletingBackupItemCauses
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.
Import Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.6 and later.
-
-
These keys access file attribute values contained in
NSDictionaryobjects used bysetAttributes:ofItemAtPath:error:,attributesOfItemAtPath:error:,createDirectoryAtPath:withIntermediateDirectories:attributes:error:, andcreateFileAtPath:contents:attributes:.Declaration
Swift
let NSFileAppendOnly: String let NSFileBusy: String let NSFileCreationDate: String let NSFileOwnerAccountName: String let NSFileGroupOwnerAccountName: String let NSFileDeviceIdentifier: String let NSFileExtensionHidden: String let NSFileGroupOwnerAccountID: String let NSFileHFSCreatorCode: String let NSFileHFSTypeCode: String let NSFileImmutable: String let NSFileModificationDate: String let NSFileOwnerAccountID: String let NSFilePosixPermissions: String let NSFileReferenceCount: String let NSFileSize: String let NSFileSystemFileNumber: String let NSFileType: StringObjective-C
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
-
NSFileAppendOnlyNSFileAppendOnlyThe 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.
-
NSFileBusyNSFileBusyThe 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.
-
NSFileCreationDateNSFileCreationDateThe 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.
-
NSFileOwnerAccountNameNSFileOwnerAccountNameThe 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.
-
NSFileGroupOwnerAccountNameNSFileGroupOwnerAccountNameThe 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.
-
NSFileDeviceIdentifierNSFileDeviceIdentifierThe 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.
-
NSFileExtensionHiddenNSFileExtensionHiddenThe 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.
-
NSFileGroupOwnerAccountIDNSFileGroupOwnerAccountIDThe 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.
-
NSFileHFSCreatorCodeNSFileHFSCreatorCodeThe key in a file attribute dictionary whose value indicates the file's HFS creator code.
The corresponding value is an
NSNumberobject containing anOSType(unsigned 32-bit integer). See HFS File Types for possible values.Available in OS X v10.1 and later.
-
NSFileHFSTypeCodeNSFileHFSTypeCodeThe key in a file attribute dictionary whose value indicates the file's HFS type code.
The corresponding value is an
NSNumberobject containing anOSType(unsigned 32-bit integer). See HFS File Types for possible values.Available in OS X v10.1 and later.
-
NSFileImmutableNSFileImmutableThe 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.
-
NSFileModificationDateNSFileModificationDateThe 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.
-
NSFileOwnerAccountIDNSFileOwnerAccountIDThe 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.
-
NSFilePosixPermissionsNSFilePosixPermissionsThe 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.
-
NSFileReferenceCountNSFileReferenceCountThe 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.
-
NSFileSizeNSFileSizeThe 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.Available in OS X v10.0 and later.
-
NSFileSystemFileNumberNSFileSystemFileNumberThe 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.
-
NSFileTypeNSFileTypeThe 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.
Discussion
NSFileDeviceIdentifieris used to access the identifier of a remote device. -
-
These strings are the possible values for the
NSFileTypeattribute key contained in the dictionary object returned byattributesOfItemAtPath:error:.Declaration
Swift
let NSFileTypeDirectory: String let NSFileTypeRegular: String let NSFileTypeSymbolicLink: String let NSFileTypeSocket: String let NSFileTypeCharacterSpecial: String let NSFileTypeBlockSpecial: String let NSFileTypeUnknown: StringObjective-C
NSString * const NSFileTypeDirectory; NSString * const NSFileTypeRegular; NSString * const NSFileTypeSymbolicLink; NSString * const NSFileTypeSocket; NSString * const NSFileTypeCharacterSpecial; NSString * const NSFileTypeBlockSpecial; NSString * const NSFileTypeUnknown;Constants
-
NSFileTypeDirectoryNSFileTypeDirectoryDirectory
Available in OS X v10.0 and later.
-
NSFileTypeRegularNSFileTypeRegularRegular file
Available in OS X v10.0 and later.
-
NSFileTypeSymbolicLinkNSFileTypeSymbolicLinkSymbolic link
Available in OS X v10.0 and later.
-
NSFileTypeSocketNSFileTypeSocketSocket
Available in OS X v10.0 and later.
-
NSFileTypeCharacterSpecialNSFileTypeCharacterSpecialCharacter special file
Available in OS X v10.0 and later.
-
NSFileTypeBlockSpecialNSFileTypeBlockSpecialBlock special file
Available in OS X v10.0 and later.
-
NSFileTypeUnknownNSFileTypeUnknownUnknown
Available in OS X v10.0 and later.
-
-
Keys to access the file attribute values contained in the dictionary object returned from the
attributesOfFileSystemForPath:error:method.Declaration
Swift
let NSFileSystemSize: String let NSFileSystemFreeSize: String let NSFileSystemNodes: String let NSFileSystemFreeNodes: String let NSFileSystemNumber: StringObjective-C
extern NSString *NSFileSystemSize; extern NSString *NSFileSystemFreeSize; extern NSString *NSFileSystemNodes; extern NSString *NSFileSystemFreeNodes; extern NSString *NSFileSystemNumber;Constants
-
NSFileSystemSizeNSFileSystemSizeThe 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.
-
NSFileSystemFreeSizeNSFileSystemFreeSizeThe 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.
-
NSFileSystemNodesNSFileSystemNodesThe 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.
-
NSFileSystemFreeNodesNSFileSystemFreeNodesThe 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.
-
NSFileSystemNumberNSFileSystemNumberThe 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.
-
-
Constants indicating the relationship between a directory and an item.
Declaration
Swift
enum NSURLRelationship : Int { case Contains case Same case Other }Objective-C
typedef enum NSURLRelationship : NSInteger { NSURLRelationshipContains, NSURLRelationshipSame, NSURLRelationshipOther } NSURLRelationship;Constants
-
ContainsNSURLRelationshipContainsThe directory contains the specified item.
Available in OS X v10.10 and later.
-
SameNSURLRelationshipSameThe directory and the item are the same. This relationship occurs when the value of the
NSURLFileResourceIdentifierKeyis the same for the directory and item.Available in OS X v10.10 and later.
-
OtherNSURLRelationshipOtherThe directory does not contain the item and is not the same as the item.
Available in OS X v10.10 and later.
Import Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.10 and later.
-
-
Specifies the version of the Foundation framework in which
NSFileManagerfirst supported resource forks.Declaration
Swift
var NSFoundationVersionWithFileManagerResourceForkSupport: Int32 { get }Objective-C
#define NSFoundationVersionWithFileManagerResourceForkSupport 412Constants
-
Sent after the iCloud (“ubiquity”) identity has changed.
When your app receives this notification, get the new token from the
NSURLRelationshipproperty. The value of that token isnilif the user has disabled iCloud. There is nouserInfodictionary.Declaration
Swift
let NSUbiquityIdentityDidChangeNotification: StringImport Statement
Objective-C
@import Foundation;Swift
import FoundationAvailability
Available in OS X v10.8 and later.
Copyright © 2016 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2015-10-30
