2010-01-20 26 views
4

所以我有點可可的n00b,但我在寫這個簡單的小程序,我不能得到的NSFileManager委託方法「shouldProceedAfterError ......」開火。這裏是我在AppDelegate中運行的代碼我瘋了嗎?用的NSFileManager委託方法shouldProceedAfterError幫助10.5+

-(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

這只是一個假設,但由於copyItemAtPath:toPath:錯誤的定義使得「在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]; 
+1

「如果你做了我們告訴你不要做的事,這不是一個錯誤。」 衛生署。我一定完全錯過了那部分。我希望我可以在委託方法中實現某種模式窗口,但是你是對的,我只需要在開始複製之前進行檢查。感謝您的迴應!我會投票,但我沒有任何代表:( – Chief 2010-01-20 20:53:08

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

調用該方法時,我注意到以下行爲:

  • 如果〜/桌面/的Source.txt是一個文件和〜/桌面/ target.txt不存在:
    • 的NSFileManager調用shouldCopyItemAtPath委託方法
  • 如果〜/桌面/的Source.txt是一個文件和〜/桌面/ target.txt存在:
    • 的NSFileManager首先調用shouldCopyItemAtPathshouldProceedAfterError
  • 如果〜/桌面/的Source.txt做不存在
    • 的NSFileManager不調用任何委託方法,只是返回一個NSError OBJET