Como verificar se existe uma pasta em Cocoa & Objective-C?
-
01-07-2019 - |
Pergunta
Como verificar se uma pasta (diretório) existe em Cocoa usando Objective-C?
Solução
método NSFileManager
de Uso fileExistsAtPath:isDirectory:
. docs See da Apple aqui .
Outras dicas
Alguns bons conselhos de Apple no NSFileManager.h sobre a verificação do sistema de arquivos:
"É muito melhor para tentar uma operação (como carregar um arquivo ou criar um diretório) e manipular o erro graciosamente do que está a tentar descobrir antes do tempo se a operação terá sucesso. A tentativa de comportamento predicado baseado no estado atual do sistema de arquivos ou um arquivo específico no sistema de arquivos está encorajando comportamento estranho em face de condições de corrida sistema de arquivos ".
[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 é o melhor lugar para procurar APIs relacionados arquivo. A API específica que você necessita é
- fileExistsAtPath:isDirectory:
.
Exemplo:
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!
}
Se o seu tem um objeto NSURL
como path
, é melhor caminho utilidade para convertê-lo em 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");