In a tabbed application developed in Xcode 4.2, I found a confusing problem: In one of tabs, there is a tableview to show something like index. So I initialized an array in viewDidLoad() method. for example:
- (void)viewDidLoad
{
NSArray *array = [NSArray arrayWithObjects:@"abc", @"def", @"ghi", @"jkl", @"mno", nil];
self.arrayList = array;
[array release];
[super viewDidLoad];
}
Then I use this arrayList in other methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrayList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [arrayList objectAtIndex:indexPath.row];
return cell;
}
But Xcode gives me the “EXC_BAD_ACCESS” signal every time I run it. I put some breakpoints, and found that the array was created successfully in viewDidLoad(), but before running the method cellForRowAtIndexPath:(NSIndexPath *)indexPath, it became a freed object. That’s the reason why I got that signal and the application crashed. So, how to solve this problem?
Btw, the view controller where the problem occurs is created from UIViewController, not UITableViewController. But I put a table view and linked its datasource and delegate to File’s Owner. Does that matter?
You must not
releasethe array. The+arrayWithObjects:convenience method returns an unowned array. You never took ownership of the array, therefore you must not relinquish ownership. Remove the the line[array release]and you will not see this error anymore (at least not for that reason).