将用户给出的数据添加到数组 - Objective-C
我试图创建一个Mac OS X应用程序,其中有一些默认声音,用户可以添加其他人,如果他想要的话。我加载的声音到一个数组中-awakeFromNib
:直到应用程序试图添加到阵列的用户增加了声音将用户给出的数据添加到数组 - Objective-C
for (NSString *str in [PreferencesController beats]) {
resourcePath = [[NSBundle mainBundle] pathForSoundResource:str];
beat = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
[beat setLoops:YES];
[beat setName:str];
[beatsArray addObject:beat];
}
,一切工作正常。它说:*** -[NSURL initFileURLWithPath:]: nil string parameter
。我猜测,它无法找到该文件的URL,但是当用户通过下面的代码选择它,我将文件复制到应用程序的目录:
if ([openDlg runModalForTypes:[NSArray arrayWithObjects:@"aif",@"aiff",@"mp3",@"wav",@"m4a",nil]] == NSOKButton)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dataPath = [[NSBundle mainBundle] bundlePath];
NSLog(@"Datapath is %@", dataPath);
NSLog(@"Selected Files : %@",[[openDlg URLs] objectAtIndex:0]);
[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error];
NSLog(@"File copied");
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:[PreferencesController beats]];
NSString *fileName = [[[openDlg URL] path] lastPathComponent];
NSArray *fileNameArray = [fileName componentsSeparatedByString:@"."];
[newArray addObject:[fileNameArray objectAtIndex:0]];
NSLog(@"%@",newArray);
[PreferencesController setBeats:newArray];
[self awakeFromNib];
[_tableView reloadData];
}
有什么不对的代码?
看起来您正在尝试将文件复制到文件夹,因为您只是使用包路径作为目标网址。目标网址需要指定包括目标文件名的完整路径。
尝试记录错误时,文件被复制:
NSLog(@"File copied with error: %@", error);
此行包含错误:
[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error];
具体来说,问题是目标URL是一个文件夹:
[[NSBundle mainBundle] bundlePath]
它应该是这样的:
[[[NSBundle mainBundle] bundlePath] stringByAppendingString:[[[[openDlg URLs] objectAtIndex:0] path] lastPathComponent];
然后,一旦你有它的工作,@Abizern在评论中说,保存到包是一个坏主意(它是应用程序的一部分)。 一旦你有它的工作,你应该选择一个更好的位置来保存声音(如应用程序的支持文档文件夹,Programmatically get path to Application Support folder)
它说:'错误域= NSCocoaErrorDomain代码= 516“”1音轨“无法复制到”调试“,因为具有相同名称的项目已经存在。”'但如果文件存在,它应该能够加载数组中的声音不? – user2331955 2013-05-03 12:12:39
如果文件夹已经存在,则不是。尝试记录您尝试加载播放声音的路径,并查看是否存在真正的声音文件。 – Wain 2013-05-03 12:14:32
其实我无法登录,因为这是错误发生的地方,它是空的...... – user2331955 2013-05-03 12:16:24
您正试图写入您的应用程序包?尝试写入文件系统。 – Abizern 2013-05-03 12:39:40