代码之家  ›  专栏  ›  技术社区  ›  Jack

iPhone(iOS):将文件从主包复制到文档文件夹错误

  •  8
  • Jack  · 技术社区  · 15 年前

    我正在尝试在首次启动时将一些文件从我的应用程序包复制到documents目录。我已经为第一次发布准备好了检查,但是为了清晰起见,代码片段中没有包含这些检查。问题是我正在复制到文档目录(已经存在),在文档中,它声明:

    dSTPATH 操作之前不能存在。

    什么是实现直接复制到文档根目录的最佳方法?我想这样做的原因是允许iTunes文件共享支持。

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
      NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Populator"];
    
      NSLog(@"\nSource Path: %@\nDocuments Path: %@", sourcePath, documentsDirectory);
    
      NSError *error = nil;
    
      if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:documentsDirectory error:&error]){
        NSLog(@"Default file successfully copied over.");
      } else {
        NSLog(@"Error description-%@ \n", [error localizedDescription]);
        NSLog(@"Error reason-%@", [error localizedFailureReason]);
      }
      ...
      return YES;
    }
    

    谢谢

    2 回复  |  直到 13 年前
        1
  •  11
  •   Vladimir    15 年前

    目标路径必须包含要复制的项目的名称,而不仅仅是文档文件夹。尝试:

    if([[NSFileManager defaultManager] copyItemAtPath:sourcePath 
              toPath:[documentsDirectory stringByAppendingPathComponent:@"Populator"]
              error:&error]){
    ...
    

    编辑: 对不起,误解了你的问题。不知道是否有更好的选项,然后遍历文件夹内容并分别复制每个项目。如果你的目标是IOS4,你可以使用NSARRAY的 -enumerateObjectsUsingBlock: 功能:

    NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];
    [resContents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
        {
            NSError* error;
            if (![[NSFileManager defaultManager] 
                      copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] 
                      toPath:[documentsDirectory stringByAppendingPathComponent:obj]
                      error:&error])
                DLogFunction(@"%@", [error localizedDescription]);
        }];
    

    另外,如果不能使用块,可以使用快速枚举:

    NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];
    
    for (NSString* obj in resContents){
        NSError* error;
        if (![[NSFileManager defaultManager] 
                     copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] 
                     toPath:[documentsDirectory stringByAppendingPathComponent:obj]
                     error:&error])
                DLogFunction(@"%@", [error localizedDescription]);
        }
    
        2
  •  6
  •   ingconti    13 年前

    注释:
    不要在DidFinishLaunchingWithOptions中发布冗长的操作:这是一个概念错误。 如果这本书花了太多时间,看门狗会杀了你。 在辅助线程或nsOperation中启动它… 我个人使用计时器程序。