0

我试图在用户库目录中创建一个文件夹,但它没有创建。下面的代码是否有任何错误。

databaseName = @"KITSMAW0051_DB.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = @"Swasstik";
databasePath = [[documentsDir stringByAppendingPathComponent:folder ] stringByAppendingPathComponent:databaseName];
4

2 回答 2

2

好的,首先databasePath描述文件的路径而不是目录。但是,假设您实际上想在用户的库中创建“Swasstik”文件夹:

// Your code
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = @"Swasstik";
// I edited here to keep only the folder
NSString *folderPath = [documentsDir stringByAppendingPathComponent:folder];

// At this point we got the path to the folder
// but we want to actually go on and create it
// NSFileManager to the rescue!
NSFileManager *manager = [NSFileManager defaultManager];
[manager createDirectoryAtPath: folderPath
 withIntermediateDirectories: NO
 attributes: nil
 error: nil];

当然你可以学习和设置你喜欢的管理器,也可以实现一些错误处理。我希望这是有道理的......

于 2012-09-26T14:47:14.197 回答
1
databaseName = @"KITSMAW0051_DB.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = [documentsDir stringByAppendingPathComponent:@"Swasstik"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]) {
    [fileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&error];
}
if (error != nil) {
    NSLog(@"Some error: %@", error);
    return;
}
NSString *databasePath = [folder stringByAppendingPathComponent:databaseName];
于 2012-09-26T14:47:46.210 回答