2008-09-19 12 views

Respuesta

70

Utilice NSFileManager método fileExistsAtPath:isDirectory:. Consulte los documentos de Apple here.

+1

No exactamente. Porque está pasando un puntero a bool como 'isDirectory'. Significa que si hay un archivo con ese nombre, este método devuelve SÍ y escribe 'NO' en el puntero' isDirectory'. – yas375

+1

Pero todo es un archivo en Unix. – uchuugaka

10

[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. 
+0

La primera línea confundió que 'fileExists..' es un método de clase. Amablemente actualiza la respuesta. Podría haberlo hecho, pero es una respuesta demasiado antigua, si es eso sería mejor. –

13

Un buen consejo de Apple en el NSFileManager.h respecto a la revisión del sistema de archivos:

"Es mucho mejor para intentar una operación (como la carga de una archivo o crear un directorio) y manejar el error con elegancia de lo que es tratar de averiguar con anticipación si la operación tendrá éxito. Intentar predicar el comportamiento basado en el estado actual del sistema de archivos o un archivo particular en el sistema de archivos es alentador impar comportamiento frente a las condiciones de carrera del sistema de archivos ".

+0

También se menciona en los documentos: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/ NSFileManager/fileExistsAtPath: – Monolo

6

NSFileManager es el mejor lugar para buscar API relacionadas con archivos. La API específico 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! 
} 
1

Si dispone de un objeto NSURL como path, es mejor utilizar 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"); 
Cuestiones relacionadas