【发布时间】:2011-11-24 09:51:57
【问题描述】:
我猜这是初学者的问题,但我试图检查 iPhone 上的 Documents 文件夹中是否存在目录。我阅读了文档并想出了这段代码,不幸的是,该代码在 BOOL fileExists 行中因 EXC_BAD_ACCESS 而崩溃:
-(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];
BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:YES];
if (fileExists)
{
NSLog(@"Folder already exists...");
}
}
我不明白我做错了什么?它对我来说看起来很完美,它当然符合文档,不是吗?任何关于我哪里出错的启示将不胜感激!谢谢。
更新:
还是不行……
-(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];
BOOL isDir;
BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:&isDir];
if (fileExists)
{
if (isDir) {
NSLog(@"Folder already exists...");
}
}
}
【问题讨论】:
-
@Legolas 根据文档检查它是否是一个目录。但我想这是我出错的地方。
-
第二个在什么意义上不起作用,仍然是一个错误的访问?还想从文档中指出:
Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed.
标签: iphone objective-c cocoa-touch nsfilemanager