xcode NSFileManager 不创建文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14518054/
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
NSFileManager doesn't create folder
提问by iWheelBuy
- (NSURL *) applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
....
....
NSURL *folder = [[[Database sharedInstance] applicationDocumentsDirectory] URLByAppendingPathComponent:@"temp"];
BOOL isFolder;
NSLog(@"URL: %@", folder);
if ([[NSFileManager defaultManager] fileExistsAtPath:folder.absoluteString isDirectory:&isFolder] == NO)
{
NSLog(@"IsFolder: %d", isFolder);
[[NSFileManager defaultManager] createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:&error];
if (error)
NSLog(@"Error: %@", error.localizedDescription);
}
I run this part of code twice.
我运行这部分代码两次。
I expect that the folder will be created, but every time I receive a log: "IsFolder: 7".
我希望文件夹会被创建,但每次我收到一个日志:“IsFolder: 7”。
Why the folder wasn't created after the first run?
为什么第一次运行后没有创建文件夹?
回答by iWheelBuy
The problem was in folder.absoluteString
.
问题出在folder.absoluteString
.
It should be folder.path
instead.
应该是这样folder.path
。
回答by Deepesh
Please, replace folder.absoluteString to folder, your problem will be solved.
请将 folder.absoluteString 替换为文件夹,您的问题将得到解决。
Follow step by step:
循序渐进:
1) Get documents folder
1) 获取文档文件夹
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
2) Get documents folder and folder name
2) 获取文档文件夹和文件夹名称
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
3) Check alerdy exists or not
3)检查alerdy是否存在
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if( [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
else
{
NSLog(@"[%@] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
}