Objective c 我疯了吗?NSFileManager委托方法的帮助应在10.5+;
所以我有点像Cocoa n00b,但我正在编写这个简单的小程序,我无法启动NSFileManager委托方法“shouldProceedAfterError…”。下面是我在AppDelegate中运行的代码Objective c 我疯了吗?NSFileManager委托方法的帮助应在10.5+;,objective-c,cocoa,nsfilemanager,Objective C,Cocoa,Nsfilemanager,所以我有点像Cocoa n00b,但我正在编写这个简单的小程序,我无法启动NSFileManager委托方法“shouldProceedAfterError…”。下面是我在AppDelegate中运行的代码 -(BOOL)copyFile { [[NSFileManager defaultManager] setDelegate:self]; NSError *copyError = nil; NSString *filename = [[NSString alloc]
-(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:©Error];
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获得了这个跟踪:所以我不确定为什么这个方法没有触发
我疯了吗?我是怎么搞砸了这里的代理实现的?谢谢你的帮助 这只是一个假设,但由于copyItemAtPath:toPath:error的定义是“在srcPath中指定的文件必须存在,而dstPath在操作之前不能存在”,因此dstPath已经存在的场景可能不被视为“错误”,因此不会触发委托
i、 e.也许“如果你做了我们告诉你不要做的事情,这不是一个错误。” 您可以随时进行检查并自己删除:
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];
可能您提供的源路径错误?
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:©Error];
NSLog(@"Error:%@", copyError);
}
调用该方法时,我注意到以下行为:
- 如果~/Desktop/source.txt是文件且~/Desktop/target.txt不存在:
- NSFileManager调用
delegate方法shouldCopyItemAtPath
- NSFileManager调用
- 如果~/Desktop/source.txt是一个文件并且~/Desktop/target.txt存在:
- NSFileManager首先调用
和shouldCopyItemAtPath
shouldProceedAfterError
- NSFileManager首先调用
- 如果~/Desktop/source.txt不存在
- NSFileManager不调用任何委托方法,只返回一个NSError对象