2012-06-25 64 views
10

我使用下面的代码行救我yoyo.txt的文件中的文档文件夹::创建一个文件夹以编程方式在Xcode中 - 目标C

NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 
NSLog(@"docDir is yoyo :: %@", docDir); 
NSString *FilePath = [docDir stringByAppendingPathComponent:@"yoyo.txt"]; 

不过,我想保存我的文件一个yoyo文件夹,即在Documents文件夹内,即我想创建另一个名为“yoyo”的文件夹,然后将我的yoyo.txt文件保存到其中。我怎样才能做到这一点 ??谢谢。

+0

Xcode的是IDE的最终路径。语言是Objective C,您可以在文本编辑器中编写相同的代码并在命令行上编译它。这是一个常见的错误,混淆了'Xcode'和'Objective C'。 –

回答

15

这里是一个示例代码(假设manager[NSFileManager defaultManager]):

BOOL isDirectory; 
NSString *yoyoDir = [docDir stringByAppendingPathComponent:@"yoyo"]; 
if (![manager fileExistsAtPath:yoyoDir isDirectory:&isDirectory] || !isDirectory) { 
     NSError *error = nil; 
     NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete 
                 forKey:NSFileProtectionKey]; 
     [manager createDirectoryAtPath:yoyoDir 
      withIntermediateDirectories:YES 
          attributes:attr 
           error:&error]; 
     if (error) 
      NSLog(@"Error creating directory path: %@", [error localizedDescription]); 
    } 
+0

什么是代码中的“isDictionary”。你在代码中声明的NSDictionary的目的是什么? – kamalbhai

+0

isDictionary是BOOL,用于检查路径中存在的文件是否为目录,因为可能有文件不是目录...字典用于在代码中为新创建的目录传递属性我有这是'该文件以加密格式存储在磁盘上,无法在设备锁定或引导时读取或写入。'您可以将'nil'传递给此设备。你也可以看到[NSFileManager类参考](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsfilemanager_Class/Reference/Reference.html) – graver

11
+(void)createDirForImage :(NSString *)dirName 
{ 
    NSString *path; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    path = [[paths objectAtIndex:0] stringByAppendingPathComponent:dirName]; 
    NSError *error; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) //Does directory already exist? 
    { 
     if (![[NSFileManager defaultManager] createDirectoryAtPath:path 
             withIntermediateDirectories:NO 
                 attributes:nil 
                  error:&error]) 
     { 
      NSLog(@"Create directory error: %@", error); 
     } 
    } 

} 
2

这里的数据路径将用于保存文件

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

     if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){ 
      [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder 
    } 
    dataPath = [dataPath stringByAppendingPathComponent:@"/yoyo.txt"]; 
相关问题