Как проверить, существует ли папка в Cocoa & Objective-C? - PullRequest
43 голосов
/ 19 сентября 2008

Как проверить, существует ли папка (каталог) в Какао с помощью Objective-C?

Ответы [ 5 ]

70 голосов
/ 19 сентября 2008

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

13 голосов
/ 23 сентября 2010

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

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

10 голосов
/ 19 сентября 2008

[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.
7 голосов
/ 21 апреля 2012

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!
}
2 голосов
/ 11 апреля 2013

Если у вас есть NSURL объект как 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");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...