Создание папки в программе Xcode - Цель C
Я использую следующую строку кода для сохранения моего файла yoyo.txt в папке Documents::
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSLog(@"docDir is yoyo :: %@", docDir);
NSString *FilePath = [docDir stringByAppendingPathComponent:@"yoyo.txt"];
Однако я хочу сохранить файл в папке yoyo, то есть внутри папки Documents, то есть хочу создать другую папку с именем "yoyo", а затем сохранить в нее файл yoyo.txt. Как мне это сделать?? Спасибо.
Ответы
Ответ 1
Вот пример кода (предположим manager
is [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]);
}
Ответ 2
+(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);
}
}
}
Ответ 3
Здесь 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"];