2011-02-06 131 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];