- (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);
}
我运行这部分代码两次。
我希望会创建该文件夹,但每次收到日志时都会显示:“IsFolder:7”。
为什么第一次运行后没有创建文件夹?
答案 0 :(得分:10)
问题出在folder.absoluteString
。
应该是folder.path
。
答案 1 :(得分:8)
请将folder.absoluteString替换为文件夹,解决问题
按照setp
进行setp1)获取文件夹
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
2)获取文档文件夹和文件夹名称
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
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?");
}