4

だから私は一種のCocoan00bですが、この単純な小さなプログラムを書いているので、NSFileManagerデリゲートメソッド「shouldProceedAfterError...」を起動させることができません。これが私のAppDelegateで実行しているコードです

-(BOOL)copyFile {
    [[NSFileManager defaultManager] setDelegate:self];

    NSError *copyError = nil;
    NSString *filename = [[NSString alloc] initWithString:[[[self.sourceFile path] componentsSeparatedByString:@"/"] lastObject]];
    NSString *destination = [[[[[UserData sharedData] folderLocation] path] stringByAppendingString:@"/"] stringByAppendingString:filename];

    [[NSFileManager defaultManager] copyItemAtPath:[self.sourceFile path] toPath:destination error:&copyError];

    NSLog(@"error! %@",copyError);

    [filename release];
    return YES;
}

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath {
    NSLog(@"more error... %@",error);
    return NO;
}
- (BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath {
    NSLog(@"in shouldCopyItemAtPath...");
    return YES;
}

私が対処しようとしている状況は、ファイルが宛先にすでに存在するかどうかです。エラーは発生しますが、「moreerror...」トレースが出力されることはありません。また、shouldCopyItemAtPathからそのトレースを取得します。そのため、メソッドが起動しない理由が正確にわかりません。

私は夢中になっていますか?ここでデリゲートの実装をどのように台無しにしましたか?助けてくれてありがとう!

4

2 に答える 2

5

これは単なる仮説ですが、copyItemAtPath:toPath:errorは、「srcPathで指定されたファイルが存在する必要があり、dstPathは操作の前に存在してはならない」ように定義されているためです。おそらく、dstPathがすでに存在するシナリオは「エラー」とは見なされないため、デリゲートは起動されません。

つまり、おそらく「私たちがやらないように言ったことをやったとしても、それは間違いではありません」。

いつでも自分でチェックして削除できます。

NSFileManager* fileManager = [NSFileManager defaultManager];

// Delete the file if it already exists.
if ([fileManager fileExistsAtPath: destination])
        if (![fileManager removeItemAtPath: destination error: error])
                return NO;

return [fileManager copyItemAtPath: source toPath: destination error: error];
于 2010-01-20T20:17:02.780 に答える
1

おそらく、ソースとして間違ったパスを提供していますか?
copyItemAtPathソースパスが無効な場合、デリゲートメソッドを呼び出しません。
次の方法を使用すると、それをテストできます。

-(IBAction)copyFile:(id)sender
{
    [[NSFileManager defaultManager] setDelegate:self];
    NSError* copyError = nil;
    NSString* sourceFilepath = [@"~/Desktop/source.txt" stringByExpandingTildeInPath];
    NSString* targetFilepath = [@"~/Desktop/target.txt" stringByExpandingTildeInPath];  
    [[NSFileManager defaultManager] copyItemAtPath:sourceFilepath toPath:targetFilepath error:&copyError];  
    NSLog(@"Error:%@", copyError);  
}

そのメソッドを呼び出すと、次の動作に気付きます。

  • 〜/ Desktop / source.txtがファイルであり、〜/ Desktop / target.txtが存在しない場合:
    • NSFileManagerはshouldCopyItemAtPathデリゲートメソッドを呼び出します
  • 〜/ Desktop / source.txtがファイルであり、〜/ Desktop / target.txtが存在する場合:
    • NSFileManagerは最初にとを呼び出しshouldCopyItemAtPathますshouldProceedAfterError
  • 〜/ Desktop/source.txtが存在しない場合
    • NSFileManagerはデリゲートメソッドを呼び出さず、NSErrorオブジェクトを返すだけです
于 2010-01-20T20:21:07.827 に答える