xcode iOS 将文件从主包复制到文档目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9230110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS copy files from main bundle to documents directory
提问by Jaume
I am trying to copy files that I add to a folder called "includes" to a folder on documents directory called also "includes".
我正在尝试将添加到名为“includes”的文件夹中的文件复制到也称为“includes”的文档目录中的文件夹中。
I get a nil value for resContents
. Why?
我得到了一个 nil 值resContents
。为什么?
- (void)copyResources{
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"includes"];
NSString *destPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"includes"];
NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:NULL];
for (NSString* obj in resContents){
NSError* error;
if (![[NSFileManager defaultManager] copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] toPath:[destPath stringByAppendingPathComponent:obj] error:&error]) {
NSLog(@"Error: %@", error);;
}
}
}
采纳答案by Ignacio Inglese
Your Xcode project should add your includes
folder as a Folder Referenceand not as a Group.
您的 Xcode 项目应该将您的includes
文件夹添加为Folder Reference而不是Group。
Groups are just meant to keep things organized rather than provide a folder structure and therefore when copying to the device, all the files end up at the same level.
组只是为了让事情井井有条,而不是提供文件夹结构,因此在复制到设备时,所有文件最终都处于同一级别。
回答by cli_hlt
Look into your compiled application bundle.
查看您编译的应用程序包。
Usually, the Xcode generated bundles are flat. This means although your added resource files will be copied to the bundle, any directories you created will not and hence there is no "includes" directory at the resource path. Consequently, your source contents will be nil.
通常,Xcode 生成的包是扁平的。这意味着尽管您添加的资源文件将被复制到包中,但您创建的任何目录都不会复制,因此资源路径中没有“includes”目录。因此,您的源内容将为零。
So in your case, try using just:
因此,在您的情况下,请尝试仅使用:
NSString *sourcePath = [[NSBundle mainBundle] resourcePath];
NSString *sourcePath = [[NSBundle mainBundle] resourcePath];
Edit: Well and obviously adding a folder reference also works (credits to Ignacio Inglese).
编辑:嗯,显然添加文件夹引用也有效(归功于 Ignacio Inglese)。