在Objective-C / cocoa中创build文件夹/目录
我有这个代码在Objective-C / cocoa中创build一个文件夹/目录。
if(![fileManager fileExistsAtPath:directory isDirectory:&isDir]) if(![fileManager createDirectoryAtPath:directory attributes:nil]) NSLog(@"Error: Create folder failed %@", directory);
它工作正常,但我得到了creatDirectoryAtPath:attributes is deprecated
警告消息。 在Cocoa / Objective-c中制作目录生成器的最新方法是什么?
解决了
BOOL isDir; NSFileManager *fileManager= [NSFileManager defaultManager]; if(![fileManager fileExistsAtPath:directory isDirectory:&isDir]) if(![fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:NULL]) NSLog(@"Error: Create folder failed %@", directory);
在find的文档中约30秒:
-[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:]
你的解决scheme是正确的,尽pipeApple在NSFileManager.h
包含了一个重要的注意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:
是多余的,可能是危险的。
为了您的需要,并且在您的问题的有限范围内,这可能不会成为问题,但是下面的解决scheme既简单又不太可能产生未来问题:
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); }
还要注意苹果的文档 :
返回值
如果该目录已创build,则为YES;如果设置了createIntermediates且该目录已存在,则为YES;如果发生错误,则为NO。
因此,将createIntermediates
设置为YES
,您事实上已经检查了该目录是否已经存在。
我想添加到这里,并从有关使用+ defaultManager方法的文档中提到更多:
在iOS和Mac OS X v 10.5及更高版本中,您应该考虑使用[[NSFileManager alloc] init]而不是单例方法defaultManager。 NSFileManager的实例在使用[[NSFileManager alloc] init]创build时被认为是线程安全的。
您可能更喜欢使用NSFileManager
方法:
createDirectoryAtURL:withIntermediateDirectories:attributes:error:
它使用URL而不是pathstring。