以编程方式创建目录

时间:2013-05-04 04:56:58

标签: ios objective-c nsfilemanager

我想在applicationSupportDirectory中创建一个目录。我的理解是applicationSupportDirectory不允许用户查看其中的数据。这就是我选择它的原因。但是,我在下面使用的代码似乎失败了,我不知道为什么。

谁能告诉我我做错了什么?谢谢!

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,   NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0]; // Get directory
NSString *dataPath = [applicationDirectory stringByAppendingPathComponent:@"drawings"];

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

NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
  ;// success
else
{
  NSLog(@"Failed");
}
}
}

3 个答案:

答案 0 :(得分:6)

尝试这个,它对我有用。

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                              NSUserDomainMask,
                                                              YES)[0];
NSString *folder = [documentsPath stringByAppendingPathComponent:@"foldername"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]){
    [fileManager createDirectoryAtPath:folder
           withIntermediateDirectories:YES
                            attributes:nil
                                 error:&error];
}

答案 1 :(得分:5)

NSString *directoryName = @"drawing";

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,   NSUserDomainMask, YES);

NSString *applicationDirectory = [paths objectAtIndex:0];
NSString *filePathAndDirectory = [applicationDirectory stringByAppendingPathComponent:directoryName];
NSError *error;

if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
                               withIntermediateDirectories:YES
                                                attributes:nil
                                                     error:&error])
{
    NSLog(@"Create directory error: %@", error);
}

希望它能帮到你

答案 2 :(得分:-1)

创建目录

NSError *error;
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/directoryname"];
NSLog(@"%@",path);
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
    // Set do not backup attribute to whole folder

}