Ваше решение правильное, хотя Apple включает важное примечание в NSFileManager.h
:
/* The following methods are of limited utility. Attempting to predicate behavior
based on the current state of the filesystem or a particular file on the
filesystem is encouraging odd behavior in the face of filesystem race conditions.
It's far better to attempt an operation (like loading a file or creating a
directory) and handle the error gracefully than it is to try to figure out ahead
of time whether the operation will succeed. */
- (BOOL)fileExistsAtPath:(NSString *)path;
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory;
- (BOOL)isReadableFileAtPath:(NSString *)path;
- (BOOL)isWritableFileAtPath:(NSString *)path;
- (BOOL)isExecutableFileAtPath:(NSString *)path;
- (BOOL)isDeletableFileAtPath:(NSString *)path;
По существу, если несколько потоков / процессов изменяют файловую систему одновременно, состояние может измениться между вызовом fileExistsAtPath:isDirectory:
и вызовом createDirectoryAtPath:withIntermediateDirectories:
, поэтому в этом контексте излишне и, возможно, опасно вызывать fileExistsAtPath:isDirectory:
.
Для ваших нужд и в рамках ограниченного объема вашего вопроса это, скорее всего, не будет проблемой, но следующее решение и проще, и дает меньше шансов на возникновение будущих проблем:
NSFileManager *fileManager= [NSFileManager defaultManager];
NSError *error = nil;
if(![fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error]) {
// An error has occurred, do something to handle it
NSLog(@"Failed to create directory \"%@\". Error: %@", directory, error);
}
Также обратите внимание на Документация Apple :
Возвращаемое значение
ДА, если каталог был создан, ДА, если задано createIntermediates
и каталог уже существует), или НЕТ, если произошла ошибка.
Итак, установка createIntermediates
в YES
, что вы уже делаете, является де-факто проверкой того, существует ли каталог.