Как проверить, существует ли папка (каталог) в Cocoa с помощью Objective-C?
Как проверить, существует ли папка в Cocoa и Objective-C?
Ответ 1
Используйте метод NSFileManager
fileExistsAtPath:isDirectory:
. См. "Документы Apple здесь.
Ответ 2
Некоторые хорошие советы от Apple в NSFileManager.h относительно проверки файловой системы:
"Намного лучше попытаться выполнить операцию (например, загрузить файл или создать каталог) и обработать ошибку изящно, чем пытаться выяснить заранее, будет ли операция успешной. Попытка предикатного поведения на основе текущее состояние файловой системы или конкретного файла в файловой системе поощряет странное поведение в условиях условий гонки файловой системы.
Ответ 3
[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.
Ответ 4
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!
}
Ответ 5
Если у вас есть объект 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");