2013-05-03 25 views
1

我試圖創建一個應用程序,它將選定的聲音文件複製到應用程序的目錄中。要做到這一點,我已經寫了下面的代碼:使用NSOpenPanel並複製選定的文件 - Objective-C

NSOpenPanel* openDlg = [NSOpenPanel openPanel]; 
[openDlg setCanChooseFiles:YES]; 
[openDlg setAllowsMultipleSelection:NO]; 
[openDlg setCanChooseDirectories:NO]; 
[openDlg setAllowedFileTypes:[NSArray arrayWithObjects:@"aif",@"aiff",@"mp3",@"wav",@"m4a",nil]]; 

if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton) 
{ 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 

    NSString *dataPath = [[NSBundle mainBundle] bundlePath]; 
    NSLog(@"Datapath is %@", dataPath); 
    NSLog(@"Selected Files : %@",[[openDlg URLs] objectAtIndex:0]); 
    if ([fileManager fileExistsAtPath:dataPath] == NO) 
    { 
     [fileManager copyItemAtPath:[[openDlg URLs] objectAtIndex:0] toPath:[[NSBundle mainBundle] bundlePath] error:&error]; 
     NSLog(@"File copied"); 

    } 
} 

的問題是,我可以選擇文件中的每個類型(不僅是AIF,WAV,MP3等),我從來沒有得到File copied。雖然,路徑是正確的。當我刪除if語句時,出現錯誤:[NSURL fileSystemRepresentation]: unrecognized selector sent to instance 0x1005a0b90。 這段代碼有什麼問題?

回答

1

您正將一個NSURL傳遞給期望NSString中的路徑的API。因爲你的描述表明[fileManager fileExistsAtPath:dataPath]

[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error]; 

而且,我猜測,該文件已經被複制到包:您可以考慮使用基於URL的API:

- (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error NS_AVAILABLE(10_6, 4_0); 

篩選返回NO(因爲你的NSLog永遠不會執行。)你可以手動檢查,或者你可以讓NSFileManager刪除任何現有文件,然後複製到新選擇的文件中。

+0

非常感謝! – user2331955 2013-05-03 11:00:06