NSArray导致EXC_BAD_ACCESS

hyd*_*dev 2 iphone uitableview nsarray

我在使用NSArray填充UITableView时遇到问题.我确定我做的事情很糟糕,但我无法理解.当我尝试做一个简单的计数时,我得到了EXC_BAD_ACCESS,我知道这是因为我试图从一个不存在的内存位置读取.

我的.h文件有这个:

@interface AnalysisViewController : UITableViewController 
{
StatsData *statsData;
NSArray *SectionCellLabels;
}
Run Code Online (Sandbox Code Playgroud)

我的.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;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢.

麦克风

sid*_*yll 8

问题出在这里:

SectionCellLabels = [NSArray arrayWithObjects:@"analysis 1",
                     @"analysis 2",
                     @"analysis 3", nil];
Run Code Online (Sandbox Code Playgroud)

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

要解决这个问题,只需添加如下retain消息:

SectionCellLabels = [[NSArray arrayWithObjects:..., nil] retain];
Run Code Online (Sandbox Code Playgroud)

并确保release阵列在另一个地方,就像你的dealloc方法一样.

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