我想在应用程序启动时将多个文件从我的NSBundle复制到Documents目录。
这是复制文件的代码:
- (NSString *) getPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingString:@"Photo.png"];
}
- (void) copyFile
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *Path = [self getPath];
BOOL success = [fileManager fileExistsAtPath:Path];
if(!success) {
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Photo.png"];
success = [fileManager copyItemAtPath:defaultPath toPath:Path error:&error];
if (!success)
NSAssert1(0, @"Failed to create writable file with message '%@'.", [error localizedDescription]);
}
}
copyFile方法将在“applicationDidFinishLaunchingWithOptions”方法中调用。但是此方法仅允许将一个文件复制到Documents目录。如果我想从NSBundle复制50个文件,这是否意味着我必须指定50个路径?有没有更短的方法,例如仅用几行代码即可获取NSBundle中的所有文件?
最佳答案
您可以从资源文件夹中复制所有文件,但是我怀疑您确实想这样做,对吗?毕竟,这些也是应用程序资源(例如仅用于UI按钮的字符串文件或图形等)
因此,您可能希望在资源文件夹中有一个子目录(例如FilesToCopy
),其中包含要复制的所有文件(例如Photo.png
在Contents/Resources/FilesToCopy/Photo.png
上找到)
要获取目录的内容,只需使用
NSError * err;
NSArray * files;
NSString * srcPath;
NSString * dstPath;
NSFileManager * man;
srcPath = [self getSrcPath];
dstPath = [self getDstPath];
man = [[NSFileManager alloc] init];
files = [man contentsOfDirectoryAtPath:srcPath error:&err];
然后您可以一次复制一个文件:
for (NSString *aFile in files) {
BOOL success;
NSString * srcFile = [srcPath stringByAppendingPathComponent:aFile];
NSString * dstFile = [dstPath stringByAppendingPathComponent:aFile];
success = [man copyItemAtPath:srcFile toPath:dstFile error:&err];
// Verify success
}
现在,您只需要
srcPath
和dstPath
。- (NSString *)getSrcPath
{
return [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"FilesToCopy"];
}
- (NSString *)getDstPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
关于iphone - 将多个文件复制到文档目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8045686/