我试图将用户生成的照片的缩略图保存在文档目录的子目录中,但我无法首先创建子目录。当我尝试在文档目录中创建子目录时出现此错误(没有这样的文件或目录):
Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)"
UserInfo=0x17ef9c90 {NSFilePath=/var/mobile/Applications/FD0CC480-97FE-4E50-931F-5341DB6AD92B/Documents/com.Jonathan.App-Name/707F0431-7A09-4D33-B122-13C48AD4CA53,
NSUnderlyingError=0x17e51520 "The operation couldn’t be completed. No such file or directory"}
我很困惑。我知道该目录不存在,因为我正在尝试创建它!我唯一能想到的是文档目录不正确,但这直接来自 Apple Docs。
我是否错误地尝试创建子目录?
- (NSURL *)documentsDirectory
{
NSFileManager *sharedFM = [NSFileManager defaultManager];
NSArray *possibleURLs = [sharedFM URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask];
NSURL *appSupportDir = nil;
NSURL *appDirectory = nil;
if ([possibleURLs count] >= 1)
{
// Use the first directory (if multiple are returned)
appSupportDir = [possibleURLs objectAtIndex:0];
}
// If a valid app support directory exists, add the
// app's bundle ID to it to specify the final directory.
if (appSupportDir)
{
NSString *appBundleID = [[NSBundle mainBundle] bundleIdentifier];
appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
}
return appDirectory;
}
- (NSURL *)thumbnailDirectoryWithName:(NSString *)theName
{
NSURL *directory = [[self documentsDirectory] URLByAppendingPathComponent:theName];
NSURL *thumbnailsDirectory = [directory URLByAppendingPathComponent:@"Thumbnails"];
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:[thumbnailsDirectory path]] == NO)
{
[[NSFileManager defaultManager] createDirectoryAtURL:thumbnailsDirectory withIntermediateDirectories:NO attributes:nil error:&error];
if (error)
{
NSLog(@"[Thumbnail Directory] %@", [error description]);
return nil;
}
}
return thumbnailsDirectory;
}
我也试过 createDirectoryAtPath:
和 stringByAppendingPathComponent:
但没有用。
thumbnailDirectoryWithName:
中的 NSURL *directory
返回:
/var/mobile/Applications/FD0CC480-97FE-4E50-931F-5341DB6AD92B/Documents/com.Jonathan.App-Name/707F0431-7A09-4D33-B122-13C48AD4CA53
文件路径的最后一个组成部分 707F0431-7A09-4D33-B122-13C48AD4CA53 是 Core Data 中实体的唯一标识符,它使我能够唯一地命名目录。
非常感谢任何帮助!
最佳答案
我接受了@danh 的回答,但我找到了出现此错误的原因。这是一个简单的错误,也是我疲倦时不应该编码的另一个原因,哈哈。我找不到 Apple 建议我们将应用程序包标识符作为子目录名称包含在内的原因,但要修复此错误,我所要做的就是设置 withIntermediateDirectories:YES
。
withIntermediateDirectories:
If YES, this method creates any non-existent parent directories as part of creating the directory in url. If NO, this method fails if any of the intermediate parent directories does not exist.
基本上,我试图在一个不存在的目录中创建一个子目录。
关于ios - "No such file or directory"创建目录时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20602726/