在 Xcode 中以编程方式创建文件夹 - 目标 C
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11187716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create A Folder Programmatically In Xcode - Objective C
提问by kamalbhai
I am using the following line of code to save my file of yoyo.txt in the Documents folder ::
我正在使用以下代码行将我的 yoyo.txt 文件保存在 Documents 文件夹中 ::
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSLog(@"docDir is yoyo :: %@", docDir);
NSString *FilePath = [docDir stringByAppendingPathComponent:@"yoyo.txt"];
However, I wish to save my file in a folder of yoyo i.e. inside the Documents folder i.e. I want to create another folder named as "yoyo" and then save my file of yoyo.txt into it. How can I do that ?? Thanks.
但是,我希望将我的文件保存在 yoyo 文件夹中,即在 Documents 文件夹内,即我想创建另一个名为“yoyo”的文件夹,然后将我的 yoyo.txt 文件保存到其中。我怎样才能做到这一点 ??谢谢。
回答by graver
Here is a sample code (assume manager
is [NSFileManager defaultManager]
):
这是一个示例代码(假设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]);
}
回答by Mani
+(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);
}
}
}
回答by Amulya
Here dataPath will be the final path for saving your file
这里 dataPath 将是保存文件的最终路径
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"];