iphone - 将多个文件复制到文档目录

标签 iphone objective-c ios cocoa-touch ipad

我想在应用程序启动时将多个文件从我的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.pngContents/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
}

现在,您只需要srcPathdstPath
- (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/

相关文章:

iphone - 反编译应用程序二进制文件以返回源代码

iphone - 使用 "self.variable = value"设置实例变量两次会导致内存泄漏吗?

iphone - 在 iOS、AVAudioRecorder 或其他设备上收听麦克风输入?

ios - 在 iOS 中获取当前位置的静态方法

iphone - 使用 NSDataDetector 检查电子邮件

ios - 从 UIWindow 中移除 UIViewController 的 View

ios - UIApplication.shared.isNetworkActivityIndi​​catorVisible 设置为 false 时崩溃

ios - 调用-reloadData后如何保持UITableView contentoffset

iphone - 如何从委托(delegate)外部设置 super View ?

ios - removeFromSuperview 函数不能正常工作