4

所以我有点像 Cocoa n00b,但我正在编写这个简单的小程序,我无法让 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;
}

我要处理的情况是该文件是否已存在于目的地。我确实得到了一个错误,但我从来没有得到那个“更多的错误......”跟踪输出。我也确实从 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 首先调用shouldCopyItemAtPathandshouldProceedAfterError
  • 如果 ~/Desktop/source.txt 不存在
    • NSFileManager 不调用任何委托方法,只返回一个 NSError 对象
于 2010-01-20T20:21:07.827 回答