8

最初の起動時に、アプリバンドルからドキュメントディレクトリにいくつかのファイルをコピーしようとしています。最初の起動時にチェックを行っていますが、わかりやすくするためにコードスニペットには含まれていません。問題は、ドキュメントディレクトリ(すでに存在している)にコピーしていることであり、ドキュメントには次のように記載されています。

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;
}

ありがとう

4

2 に答える 2

11

宛先パスには、ドキュメントフォルダーだけでなく、コピーするアイテムの名前が含まれている必要があります。試す:

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]);
    }];

PSブロックを使用できない場合は、高速列挙を使用できます。

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]);
    }
于 2010-07-14T12:50:37.557 に答える
6

注:
didFinishLaunchingWithOptionsで長時間の操作を発行しないでください:これは概念上の誤りです。このコピーに時間がかかりすぎると、ウォッチドッグがあなたを殺します。セカンダリスレッドまたはNSOperationで起動します...私は個人的にタイマープロシージャを使用します。

于 2011-09-04T08:29:13.323 に答える