Come verificare se esiste una cartella in Cocoa e Objective-C?
-
01-07-2019 - |
Domanda
Come verificare se esiste una cartella (directory) in Cocoa utilizzando Objective-C?
Soluzione
Utilizzo NSFileManager
'S fileExistsAtPath:isDirectory:
metodo.Vedi i documenti di Apple Qui.
Altri suggerimenti
Alcuni buoni consigli da Apple in NSFileManager.h riguardo al controllo del file system:
"È molto meglio tentare un'operazione (come caricare un file o creare una directory) e gestire l'errore con garbo piuttosto che cercare di capire in anticipo se l'operazione avrà successo.Tentare di predire un comportamento basato sullo stato corrente del filesystem o su un particolare file sul filesystem sta incoraggiando comportamenti strani di fronte alle condizioni di competizione del filesystem."
[File NSFileManagerExistsAtPath: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 è il posto migliore in cui cercare le API relative ai file.L'API specifica di cui hai bisogno è - fileExistsAtPath:isDirectory:
.
Esempio:
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 hai un NSURL
oggetto come path
, è meglio usare path per convertirlo in 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");