使用NSOpenPanel并复制选定的文件 - Objective-C
问题描述:
我试图创建一个应用程序,它将选定的声音文件复制到应用程序的目录中。要做到这一点,我已经写了下面的代码:使用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
。 这段代码有什么问题?
答
您正将一个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
删除任何现有文件,然后复制到新选择的文件中。
非常感谢! – user2331955 2013-05-03 11:00:06