2011-02-06 64 views
2

我使用NSArray填充UITableView時遇到問題。我確信我正在做一些愚蠢的事情,但我無法弄清楚。當我嘗試做一個簡單的計數時,我得到了EXC_BAD_ACCESS,我知道這是因爲我試圖從不存在的內存位置讀取數據。NSArray導致EXC_BAD_ACCESS

我.h文件中有這樣的:

@interface AnalysisViewController : UITableViewController 
{ 
StatsData *statsData; 
NSArray *SectionCellLabels; 
} 

我的.m有這樣的:

- (void)viewWillAppear:(BOOL)animated 
{ 
[super viewWillAppear:animated]; 
NSLog(@"AnalysisViewController:viewWillAppear"); 

// Step 1 - Create the labels array 
SectionCellLabels = [NSArray arrayWithObjects:@"analysis 1", 
        @"analysis 2", 
        @"analysis 3", nil]; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
NSLog(@"AnalysisViewController:cellForRowAtIndexPath"); 

// Check for reusable cell first, use that if it exists 
UITableViewCell *cell = [tableView  
       dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 

// If there is no reusable cell of this type, create a new one 
if (!cell) { 
    cell = [[[UITableViewCell alloc] 
      initWithStyle:UITableViewCellStyleDefault 
      reuseIdentifier:@"UITableViewCell"] autorelease]; 
} 

    /******* The line of code below causes the EXC_BAD_ACCESS error *********/ 
NSLog(@"%d",[SectionCellLabels count]); 

return cell; 
} 

任何幫助極大的讚賞。

邁克

回答

8

的問題是在這裏:

SectionCellLabels = [NSArray arrayWithObjects:@"analysis 1", 
        @"analysis 2", 
        @"analysis 3", nil]; 

你的陣列會被自動釋放,因此在方法結束它可能無法訪問了。

爲了解決這個問題,只需追加retain消息是這樣的:

SectionCellLabels = [[NSArray arrayWithObjects:..., nil] retain]; 

而且一定要release陣列中的另一個地方,就像你dealloc方法。

一個額外的提示,你可能希望使用小寫的第一個字符的名稱,所以他們似乎不是類。你甚至可以注意到這個困惑的StackOverflow的突出顯示。

+0

非常感謝。我真的很困難於Objective C的保留/釋放內存管理方面。你怎麼知道汽車什麼時候發佈,什麼時候沒有發佈? :-s – hydev 2011-02-06 17:32:07

1

試試這個

SectionCellLabels = [[NSArray arrayWithObjects:@"analysis 1", 
        @"analysis 2", 
        @"analysis 3", nil] retain];