2
- (NSURL *) applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

……

NSURL *folder = [[[Database sharedInstance] applicationDocumentsDirectory] URLByAppendingPathComponent:@"temp"];
BOOL isFolder;
NSLog(@"URL: %@", folder);
if ([[NSFileManager defaultManager] fileExistsAtPath:folder.absoluteString isDirectory:&isFolder] == NO)
{
    NSLog(@"IsFolder: %d", isFolder);
    [[NSFileManager defaultManager] createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:&error];
    if (error)
        NSLog(@"Error: %@", error.localizedDescription);
}

我运行这部分代码两次。

我希望该文件夹将被创建,但每次我收到一个日志:“IsFolder:7”。

为什么第一次运行后没有创建文件夹?

4

2 回答 2

10

问题出在folder.absoluteString.

应该是folder.path

于 2013-01-25T08:51:58.620 回答
8

请将 folder.absoluteString 替换为文件夹,您的问题将得到解决。

循序渐进:

1) 获取文档文件夹

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0]; 

2) 获取文档文件夹和文件夹名称

NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];

3)检查alerdy是否存在

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){

    NSError* error;
    if(  [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])

        else
        {
            NSLog(@"[%@] ERROR: attempting to write create MyFolder directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
于 2013-01-25T08:38:14.337 回答