views:

3953

answers:

4

How to check if a folder exists in objective-c?

A: 

This is platform dependent. On POSIX systems, use the stat() system call. On Windows, uhm, there's probably something in the Windows API for this too.

Thomas
+16  A: 

Use NSFileManager's fileExistsAtPath:isDirectory: method. See Apple's docs here.

Matt Dillard
+3  A: 

[NSFileManager fileExistsAtPath:isDirectory:]

Returns a Boolean value that indicates whether a specified file exists.

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

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

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

Return Value
YES if there is a file or directory at path, otherwise NO. If path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file or directory at the link destination.
lajos
+1  A: 

Some good advice from Apple in the NSFileManager.h regarding checking the file system:

"It's far better to attempt an operation (like loading a file or creating a directory) and handle the error gracefully than it is to try to figure out ahead of time whether the operation will succeed. Attempting to predicate behavior based on the current state of the filesystem or a particular file on the filesystem is encouraging odd behavior in the face of filesystem race conditions."

Ryan Bavetta