質問

I have the following code that returns an NSArray of the names of files in a given directory. This works fine when the directory exists but what I would like to know is how I can first check whether or not the directory at directoryPath actually exists.

NSString *directoryPath = [documentsDirectory stringByAppendingPathComponent:folderName];
NSArray *directoryContents = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:directoryPath error:nil];
役に立ちましたか?

解決

The NSFileManager class has a built in method, which is used to check if a file exists at a path or not.

The function goes like this :

[fileManagerObject fileExistsAtPath : @"PUT_YOUR_FILE_PATH_HERE" isDirectory : YES]; //If its a file that you're looking to check then put isDirectory as NO, but if its a folder then enter YES as the parameter

Here's how you would typically use it in your code :

NSFileManager *fileManager = [[NSFileManager alloc] init];
if([fileManager fileExistsAtPath:@"FILE_PATH_HERE" isDirectory:NO] == YES)
{
   //Yes. The file exists, continue with your operation.
}
else
{
   //No. The file doesn't exist.
}

他のヒント

Use NSFileManager's fileExistsAtPath:isDirectory: method.

fileExistsAtPath:isDirectory:

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.

Apple Documentation for NSFileManager

Following NSFileManger API can give the desired results:

fileExistsAtPath:isDirectory:

Use this :

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *pathToDocumentsDir = [paths objectAtIndex:0];
    BOOL isDir;
    NSString *subfolder = [pathToDocumentsDir stringByAppendingPathComponent:fileExistsAtPath:YOUR_DIRECTORY_NAME];
    if (![fileManager fileExistsAtPath:subfolder isDirectory:&isDir]) {

//No directory exist
         [fileManager createDirectoryAtPath:subfolder withIntermediateDirectories:NO attributes:nil error:nil];
    }
else{
//directory exist
}

Sample code:

NSString *directoryPath = [documentsDirectory stringByAppendingPathComponent:folderName];
BOOL isDirectory;
BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDirectory];
if (isExists) {
    /* file exists */
    if (isDirectory) {
        /* file is a directory */

    }
 }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top