Pregunta

¿Cómo comprobar si existe una carpeta (directorio) en Cocoa usando Objective-C?

¿Fue útil?

Solución

Usar NSFileManager's fileExistsAtPath:isDirectory: método.Ver los documentos de Apple aquí.

Otros consejos

Algunos buenos consejos de Apple en NSFileManager.h con respecto a verificar el sistema de archivos:

"Es mucho mejor intentar una operación (como cargar un archivo o crear un directorio) y manejar el error con elegancia que intentar averiguar de antemano si la operación tendrá éxito.Intentar predicar el comportamiento basándose en el estado actual del sistema de archivos o en un archivo particular en el sistema de archivos está fomentando un comportamiento extraño frente a las condiciones de carrera del sistema de archivos".

[El archivo NSFileManager existe en la ruta: esDirectorio:]

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.

NSFileManager es el mejor lugar para buscar API relacionadas con archivos.La API específica que necesita es - fileExistsAtPath:isDirectory:.

Ejemplo:

NSString *pathToFile = @"...";
BOOL isDir = NO;
BOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:pathToFile isDirectory:&isDir];

if(isFile)
{
    //it is a file, process it here how ever you like, check isDir to see if its a directory 
}
else
{
    //not a file, this is an error, handle it!
}

Si tienes un NSURL objeto como path, es mejor usar la ruta para convertirlo en NSString.

NSFileManager*fm = [NSFileManager defaultManager];

NSURL* path = [[[fm URLsForDirectory:NSDocumentDirectory 
                           inDomains:NSUserDomainMask] objectAtIndex:0]                           
                                 URLByAppendingPathComponent:@"photos"];

NSError *theError = nil;
if(![fm fileExistsAtPath:[path path]]){
    NSLog(@"dir doesn't exists");
}else
    NSLog(@"dir exists");
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top