将多个文件复制到Documents目录

Llo*_*rth 1 iphone cocoa-touch objective-c ipad ios

我想在应用程序启动时将多个文件从我的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]);
  }
}
Run Code Online (Sandbox Code Playgroud)

copyFile方法将在'applicationDidFinishLaunchingWithOptions'方法中调用.但是此方法仅允许将一个文件复制到Documents目录.如果我想从我的NSBundle复制50个文件,这是否意味着我必须指定50个路径?有没有更短的方法,例如只用几行代码获取NSBundle中的所有文件?

Mec*_*cki 6

你可以复制资源文件夹中的所有文件,但我怀疑你真的想这样做,对吗?毕竟这些也是应用程序资源(如字符串文件或仅用于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];
Run Code Online (Sandbox Code Playgroud)

然后您可以一次复制一个文件:

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
}
Run Code Online (Sandbox Code Playgroud)

现在你只需要srcPathdstPath.

- (NSString *)getSrcPath
{
     return [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"FilesToCopy"];
}

- (NSString *)getDstPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}
Run Code Online (Sandbox Code Playgroud)