无法在文档目录中创建文件夹

时间:2014-07-30 09:16:58

标签: ios nsbundle nsdocumentdirectory

我开发了iPhone应用程序,其中我一度陷入困境,

我想做的是, 我想将我的数据库从bundle复制到folder inside document directory

当我尝试在DocDir内创建文件夹时,它没有被创建并且显示错误,

无法创建带有消息的MyDB.sql文件'无法完成操作。 (可可错误4。)

这是我的代码段,

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [[paths objectAtIndex:0] stringByAppendingString:@"/NewFolder/"];

    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"MyDB.sql"];
    BOOL success = [fileManager fileExistsAtPath:dbPath];

    if(!success) {

        NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"MyDB" ofType:@"sql"];

        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success)
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }

我在哪里做错了?请帮忙

提前致谢。

1 个答案:

答案 0 :(得分:4)

尝试通过以下代码创建目录,可以获得帮助..

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/YourFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])//Check
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Will Create folder