简体   繁体   English

iOS将文件从主包复制到文档目录

[英]iOS copy files from main bundle to documents directory

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 . 我得到resContents的零值。 Why? 为什么?

- (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);;
        }
    }
}

Your Xcode project should add your includes folder as a Folder Reference and not as a Group . 您的Xcode项目应将您的includes文件夹添加为文件夹参考而不是

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. 组只是为了保持组织而不是提供文件夹结构,因此在复制到设备时,所有文件最终都处于同一级别。

Look into your compiled application bundle. 查看已编译的应用程序包。

Usually, the Xcode generated bundles are flat. 通常,Xcode生成的包是扁平的。 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. 因此,您的源内容将为零。

So in your case, try using just: 所以在你的情况下,尝试使用:

NSString *sourcePath = [[NSBundle mainBundle] resourcePath];

Edit: Well and obviously adding a folder reference also works (credits to Ignacio Inglese). 编辑:嗯,显然添加文件夹引用也有效(信用Ignacio Inglese)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM