Как проверить, существует ли папка в Cocoa и Objective-C?

StackOverflow https://stackoverflow.com/questions/99395

  •  01-07-2019
  •  | 
  •  

Вопрос

Как проверить, существует ли папка (directory) в Cocoa, используя Objective-C?

Это было полезно?

Решение

Использование NSFileManager's fileExistsAtPath:isDirectory: способ.Смотрите документы Apple здесь.

Другие советы

Несколько полезных советов от Apple из NSFileManager.h относительно проверки файловой системы:

"Гораздо лучше попытаться выполнить операцию (например, загрузить файл или создать каталог) и корректно обработать ошибку, чем пытаться заранее выяснить, будет ли операция успешной.Попытка предопределить поведение на основе текущего состояния файловой системы или конкретного файла в файловой системе поощряет странное поведение перед лицом условий гонки файловой системы ".

[NSFileManager fileExistsAtPath:является каталогом:]

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 - лучшее место для поиска API, связанных с файлами.Конкретный API, который вам требуется, это - fileExistsAtPath:isDirectory:.

Пример:

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!
}

Если у вас есть NSURL объект как path, лучше использовать path для преобразования его в 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");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top