Question

Comment vérifier si un dossier (répertoire) existe dans Cocoa avec Objective-C?

Était-ce utile?

La solution

Utilisez la méthode fileExistsAtPath: isDirectory: de NSFileManager . Voir la documentation d'Apple ici .

Autres conseils

Quelques bons conseils d’Apple dans NSFileManager.h concernant la vérification du système de fichiers:

"Il est de loin préférable de tenter une opération (comme de charger un fichier ou de créer un répertoire) et de gérer l'erreur correctement, plutôt que d'essayer de déterminer à l'avance si l'opération aboutira. Tenter de prédire le comportement en fonction de l'état actuel du système de fichiers ou d'un fichier particulier sur le système de fichiers encourage un comportement étrange face aux conditions de concurrence du système de fichiers. "

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

NSFileManager est le meilleur endroit pour rechercher des API liées aux fichiers. L'API spécifique dont vous avez besoin est   isDirectory: .

Exemple:

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 vous avez un objet NSURL en tant que chemin , il est préférable d'utiliser chemin pour le convertir 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");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top