为什么我不能使用此代码创建文件夹?

时间:2011-07-14 14:54:57

标签: iphone objective-c ios

我正在尝试在我/文件中创建一个名为/coffeeShops的文件夹。我的应用程序中有以下代码:didFinishLaunchingWithOptions

 NSArray *dirPaths;
    NSString *docsDir;

    NSFileManager *manager;
    NSError *error;

manager =[NSFileManager defaultManager];


dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                               NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];
NSString *coffeeString=[NSString stringWithFormat:@"@/@",docsDir,@"coffeeShops"];

if (![manager fileExistsAtPath:coffeeString isDirectory:YES]) 
{
    [manager createDirectoryAtPath:coffeeString withIntermediateDirectories:YES attributes:nil error:&error];


    NSLog(@"Creating folder");
    if(error) NSLog(error);
}
else NSLog(@"Folder for coffee pics exists");

我在

获得了EXC_BAD_ACCESS
if (![manager fileExistsAtPath:coffeeString isDirectory:YES]) 

我做错了什么?

1 个答案:

答案 0 :(得分:3)

isDirectory旨在告诉您指定的文件是否是目录,而不是为了说“只请目录”。

请改为尝试:

BOOL isDirectory = NO;
BOOL exists = [manager fileExistsAtPath:coffeeString isDirectory:&isdirectory];
if (NO == exists || NO == isDirectory) {

@Evan确实有一个答案,它有一些更有用的点,但它已经消失了:(

NSString上有一个为你构建路径的方法 - 它叫做stringByAppendingPathComponent。我认为你应该像这样使用它:

NSString *coffeeString=[docsDir stringByAppendingPathComponent:@"coffeeShops"];