我有代码在NSHomeDirectory下创建一个文件夹,但它总是失败,我看不出原因。它应该工作,但它一直说不允许操作。有什么想法吗?
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");
}
}
答案 0 :(得分:4)
您无权访问NSHomeDirectory(),
而是在文档目录中创建它们
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSURL *homeURL = [NSURL fileURLWithPath:documentDirectory isDirectory:YES];
NSURL *previewsURL = [homeURL URLByAppendingPathComponent:@"Previews"];
答案 1 :(得分:1)
首先,正如其他答案所指出的,您无权访问主目录。
然后,我发现你想要保存某种预览:它们是用户生成的图像,是需要要保存,还是只是某些缓存的数据,只是写入加快某种过程(下载的图像,较大版本图像的缓存预览......)?
如果是这种情况,则不应使用文档目录,因为它应仅用于保存用户生成的内容,即您的应用无法自行重新创建的内容。用于此类目的的正确目录是缓存目录。如果您不遵守此协议,AppStore审核流程可能会拒绝您的应用程序。
NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSURL *cacheURL = [NSURL fileURLWithPath:cacheDirectory isDirectory:YES];
NSURL *previewsURL = [cacheURL URLByAppendingPathComponent:@"Previews"];
答案 2 :(得分:0)
简单:因为你不能/不允许写入该目录(因为它在app沙箱之外)。