在这里,我想实现一个函数,它可以从主包(从main手动添加到Xcode项目)(图1)复制res文件到Document文件夹。
为了实现这个目标,我使用了NSFileManager。以下是函数代码:
- (void)addCamConfig {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:CAM_CONFIG];
if (![fileManager fileExistsAtPath:destPath]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"cam" ofType:@"yaml"];
BOOL ret = [fileManager copyItemAtPath:sourcePath toPath:destPath error:&error];
if (error) {
NSLog(@"cam_ret:%d\nsourcePath:%@\ndestPath:%@\nerror:%@",ret,sourcePath,destPath,error.description);
}
}
}
在这种情况下,sourcePath和destPath都被保证不为零。
但是第一次发生了奇怪的事情,"copyItemAtPath:sourcePath toPath:destPath error:& error“返回"NO”,错误日志如下所示:
sourcePath:/private/var/containers/Bundle/Application/3DF49723-E11D-4D67-AD0F-39C2B82B80A4/NitroDemo.app/cam.yaml destPath:/var/mobile/Containers/Data/Application/181F8B72-402B-4D0C-91D5-0D9759BC607E/Documents/nitro/cam.yaml错误: cam_ret:0 Domain=NSCocoaErrorDomain Code=4“文件”“cam.yaml”不存在。UserInfo={NSSourceFilePathErrorKey=/private/var/containers/Bundle/Application/3DF49723-E11D-4D67-AD0F-39C2B82B80A4/NitroDemo.app/cam.yaml,NSUserStringVariant=( ),NSDestinationFilePath=/var/mobile/Containers/Data/Application/181F8B72-402B-4D0C-91D5-0D9759BC607E/Documents/nitro/cam.yaml,NSFilePath=/private/var/containers/Bundle/Application/3DF49723-E11D-4D67-AD0F-39C2B82B80A4/NitroDemo.app/cam.yaml,NSUnderlyingError=0x2826476f0 {Error Domain=NSPOSIXErrorDomain Code=2“无此类文件或目录”}}
令人惊讶的是,当我第二次运行项目时,错误消失了,"copyItemAtPath:sourcePath toPath:destPath错误:& error“返回"YES”。
如果我从我的iPhone中删除这个应用程序,然后重建项目,重新安装并第一次运行应用程序,同样的错误信息会再次出现。正如我所预期的,当我第二次运行这个项目时,错误消失了。
所以我想知道第一次和第二次究竟发生了什么?
====================
更新:我通过创建一个中间文件夹nitro
解决了这个问题。
这里的关键点是,正如您在日志中可能没有注意到的那样,XXX/Documents/nitro/cam.yaml
路径包含一个不存在的中间文件夹nitro
。因此,当我第一次调用copyItemAtPath:sourcePath toPath:destPath error:&error
时,它会失败,并可能创建该文件夹(仅供我猜测)。因此,当我第二次运行时,copyItemAtPath:sourcePath toPath:destPath error:&error
返回YES。
发布于 2020-07-29 06:30:08
好的,根据更新,您可以通过插入下面的内容来解决这个问题。
[NSFileManager.defaultManager createDirectoryAtPath:newDir
withIntermediateDirectories:YES
attributes:nil
error:NULL];
https://stackoverflow.com/questions/63129789
复制相似问题