繁体   English   中英

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

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

我正在尝试将我添加到名为“includes”的文件夹中的文件复制到名为“includes”的文档目录中的文件夹中。

我得到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);;
        }
    }
}

您的Xcode项目应将您的includes文件夹添加为文件夹参考而不是

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

查看已编译的应用程序包。

通常,Xcode生成的包是扁平的。 这意味着虽然您添加的资源文件将被复制到捆绑包,但您创建的任何目录都不会,因此资源路径中没有“包含”目录。 因此,您的源内容将为零。

所以在你的情况下,尝试使用:

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

编辑:嗯,显然添加文件夹引用也有效(信用Ignacio Inglese)。

暂无
暂无

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

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