9

基本的に、ファイルシステム内の 2 つのフォルダーを cocoa API とマージする方法を探しています。

ファイルとサブフォルダーを含むフォルダーがあり、ファイル システム内の別の場所にコピーしたいと考えています。
宛先パスには、同じ名前のフォルダーが既に存在し、ファイルやフォルダーも含まれている可能性があります。

ここで、宛先フォルダー (またはそのサブフォルダー) 内の既存のファイルが同じ名前の場合、ソース フォルダーの新しいコンテンツで上書きしたいと考えています。
残りのすべてのファイルはそのままにしておきます。

sourcefolder
   |
   - file1
   - subfolder
       - file2


destinationfolder
   |
   - file3
   - subfolder
       - file2
       - file4


resultingfolder
   |
   - file1
   - file3
   - subfolder
       - file2      <-- version from source folder
       - file4

どうやってやるの?助けてくれてどうもありがとう!

4

3 に答える 3

8

私はいたるところを探しましたが、何も見つかりませんでした。そこで、を利用して独自のソリューションを考え出しましたNSDirectoryEnumerator。これでダイアグラムが機能するはずです(古いファイルを上書きします)。それが役に立てば幸い。

- (void)mergeContentsOfPath:(NSString *)srcDir intoPath:(NSString *)dstDir error:(NSError**)err {

    NSLog(@"- mergeContentsOfPath: %@\n intoPath: %@", srcDir, dstDir);

    NSFileManager *fm = [NSFileManager defaultManager];
    NSDirectoryEnumerator *srcDirEnum = [fm enumeratorAtPath:srcDir];
    NSString *subPath;
    while ((subPath = [srcDirEnum nextObject])) {

        NSLog(@" subPath: %@", subPath);
        NSString *srcFullPath =  [srcDir stringByAppendingPathComponent:subPath];
        NSString *potentialDstPath = [dstDir stringByAppendingPathComponent:subPath];

        // Need to also check if file exists because if it doesn't, value of `isDirectory` is undefined.
        BOOL isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:srcFullPath isDirectory:&isDirectory] && isDirectory);

        // Create directory, or delete existing file and move file to destination
        if (isDirectory) {
            NSLog(@"   create directory");
            [fm createDirectoryAtPath:potentialDstPath withIntermediateDirectories:YES attributes:nil error:err];
            if (err && *err) {
                NSLog(@"ERROR: %@", *err);
                return;
            }
        }
        else {
            if ([fm fileExistsAtPath:potentialDstPath]) {
                NSLog(@"   removeItemAtPath");
                [fm removeItemAtPath:potentialDstPath error:err];
                if (err && *err) {
                    NSLog(@"ERROR: %@", *err);
                    return;
                }
            }

            NSLog(@"   moveItemAtPath");
            [fm moveItemAtPath:srcFullPath toPath:potentialDstPath error:err];
            if (err && *err) {
                NSLog(@"ERROR: %@", *err);
                return;
            }
        }
    }
}
于 2014-09-20T18:06:47.863 に答える
1

ファイル マネージャーのメソッドを確認し、デフォルトのファイル マネージャーを使用する代わりに、alloc/init を使用して独自のファイル マネージャーを作成し、デリゲートを設定して、デリゲート メソッドを使用します。

于 2014-09-29T09:50:12.063 に答える