2013-05-03 51 views
0

我試圖創建一個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]; 
} 

有什麼不對的代碼?

+0

您正試圖寫入您的應用程序包?嘗試寫入文件系統。 – Abizern 2013-05-03 12:39:40

回答

-1

看起來您正在嘗試將文件複製到文件夾,因爲您只是使用包路徑作爲目標網址。目標網址需要指定包括目標文件名的完整路徑。

嘗試記錄錯誤時,文件被複制:

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

+0

它說:'錯誤域= NSCocoaErrorDomain代碼= 516「」1音軌「無法複製到」調試「,因爲具有相同名稱的項目已經存在。」'但如果文件存在,它應該能夠加載數組中的聲音不? – user2331955 2013-05-03 12:12:39

+0

如果文件夾已經存在,則不是。嘗試記錄您嘗試加載播放聲音的路徑,並查看是否存在真正的聲音文件。 – Wain 2013-05-03 12:14:32

+0

其實我無法登錄,因爲這是錯誤發生的地方,它是空的...... – user2331955 2013-05-03 12:16:24