在Xcode中以编程方式创建文件夹 - 目标C.

kam*_*hai 11 iphone xcode objective-c ipad ios

我使用以下代码行将我的yoyo.txt文件保存在Documents文件夹中::

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

但是,我希望将我的文件保存在yoyo的文件夹中,即在Documents文件夹中,即我想创建另一个名为"yoyo"的文件夹,然后将我的yoyo.txt文件保存到其中.我怎样才能做到这一点 ??谢谢.

gra*_*ver 16

这是一个示例代码(假设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]);
    }
Run Code Online (Sandbox Code Playgroud)


Man*_*ani 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);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)