NSArray导致EXC_BAD_ACCESS

时间:2011-02-06 16:09:14

标签: iphone uitableview nsarray

我在使用NSArray填充UITableView时遇到问题。我确定我做的事情很糟糕,但我无法理解。当我尝试做一个简单的计数时,我得到了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;
}

非常感谢任何帮助。

麦克

2 个答案:

答案 0 :(得分:8)

问题在于:

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

你的数组是自动释放的,所以在方法结束时它可能不再可访问了。

要解决此问题,只需添加retain消息,如下所示:

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

请确保release数组位于其他位置,例如您的dealloc方法。

一个额外的提示,您可能希望使用小写的第一个字符的名称,因此它们似乎不是类。你甚至可以注意到这个混乱的StackOverflow的突出显示。

答案 1 :(得分:1)

试试这个

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