Returns a Boolean value that indicates whether a file or directory exists at a specified path.
SDKs
- iOS 2.0+
- macOS 10.0+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
Framework
- Foundation
Declaration
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory;
Parameters
path
The path of a file or directory. If
path
begins with a tilde (~
), it must first be expanded withstring
, or this method will returnBy Expanding Tilde In Path NO
.isDirectory
Upon return, contains
YES
ifpath
is a directory or if the final path element is a symbolic link that points to a directory; otherwise, containsNO
. Ifpath
doesn’t exist, this value is undefined upon return. PassNULL
if you do not need this information.
Return Value
YES
if a file at the specified path exists, or NO
if the file’s does not exist or its existence could not be determined.
Discussion
If the file at path
is inaccessible to your app, perhaps because one or more parent directories are inaccessible, this method returns NO
. If the final element in path
specifies a symbolic link, this method traverses the link and returns YES
or NO
based on the existence of the file at the link destination.
If you need to further determine whether path
is a package, use the is
method of NSWorkspace
.
Listing 1 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];
// ...
Note
Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It’s far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file-system race conditions, see Race Conditions and Secure File Operations in Secure Coding Guide.