2011-04-16 33 views
0

我有一個問題,出於某種原因,我無法自己弄清楚。執行sortedArrayUsingSelector後tableView錯誤

我所擁有的是從數組加載的tableView,它是從文件加載的。 (我聲明我的數組作爲NSArray的頭文件)

NSString *subMenuFileList = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"plist"]; // file list name/location 
sectionsArray = [[NSArray alloc] initWithContentsOfFile:subMenuFileList];//loading my array with the contents of the file 

我所擁有的一切工作正常,我的桌子部分我用sectionsArray.count

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
return sectionsArray.count; // return number of rows 

,爲cell.textLabel.text我有以下代碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

cell.textLabel.text= [sectionsArray objectAtIndex:indexPath.row];// get cell name from the array at row# 
return cell; 

也正常工作。

我遇到的問題是,加載的文件不是按字母順序排列的,所以我的數組原來不是按字母順序排列的。我對這個問題的解決辦法是將文件加載到一個臨時數組,排序,然後將其與下面簡單的代碼分配給部分數組:這個簡單的tweek後

NSString *subMenuFileList = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"plist"]; // file list name/location 
tempArray = [[NSArray alloc] initWithContentsOfFile:subMenuFileList]; 
sectionsArray = [tempArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];// my new sorted array 

出於某種原因,沒有其他的函數可以訪問我得到EXC_BAD ACCESS當程序試圖確定行數或單元textLabel中的行數看到圖片文件(http://img846.imageshack.us/i/screenshot20110416at141.png/)。我無法弄清楚爲什麼會發生這種情況,因爲變量是全局變量,當我爲NSArrayArray.count執行NSLog時,它會打印出適當的值。

任何幫助將非常感激。謝謝!!

回答

1
sectionsArray = [tempArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 

這將導致一個自動釋放數組。你可以保留它。

sectionsArray = [[tempArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] retain]; 

一般來說,我推薦使用屬性爲您sectionsarray(非原子,保留)..那麼這是你的代碼:

NSArray* tempArray = [[NSArray alloc] initWithContentsOfFile:subMenuFileList]; 
self.sectionsArray = [tempArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 
[tempArray release]; 

最好的問候, 基督教

+0

真棒,我完全忘了它是autoreleased。謝謝你的工作。 – Mike 2011-04-16 19:18:58

+0

當您的問題已完全解答時,請檢查左側的框;)。 – cweinberger 2011-04-16 19:27:47