本文介绍了无法在 NSHomeDirectory 下创建目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在 NSHomeDirectory 下创建文件夹的代码,但它总是失败,我不明白为什么.它应该可以工作,但它一直说不允许该操作.有什么想法吗?

I have code which creates a folder under the NSHomeDirectory but it always fails and I cannot see why. It should work but it keeps saying the operation is not permitted. Any ideas?

NSURL *homeURL = [NSURL fileURLWithPath:NSHomeDirectory() isDirectory:YES];
NSURL *previewsURL = [homeURL URLByAppendingPathComponent:@"Previews"];

DebugLog(@"homeURL: %@", homeURL);
DebugLog(@"previewsURL: %@", previewsURL);

BOOL isDirectory = TRUE;
if (![[NSFileManager defaultManager] fileExistsAtPath:previewsURL.path isDirectory:&isDirectory]) {
    DebugLog(@"isDirectory: %@", isDirectory ? @"YES" : @"NO");
    NSAssert(isDirectory, @"Must be a directory");

    NSError *error = nil;
    if (![[NSFileManager defaultManager] createDirectoryAtPath:previewsURL.path withIntermediateDirectories:TRUE attributes:nil error:&error]) {
        DebugLog(@"Error: %@", error); // WHY?!
    }
    else {
        BOOL isDirectory = TRUE;
        BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:previewsURL.path isDirectory:&isDirectory];
        NSAssert(exists, @"Directory must exist");
    }
}

推荐答案

您无权访问NSHomeDirectory(),

You have no permission to access NSHomeDirectory(),

相反,在文档目录中创建它们

Instead, create them in the documents directory

NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSURL *homeURL = [NSURL fileURLWithPath:documentDirectory isDirectory:YES];
NSURL *previewsURL = [homeURL URLByAppendingPathComponent:@"Previews"];

这篇关于无法在 NSHomeDirectory 下创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 06:20