I am programming my first iPhone app (which crashes with an EXC BAD ACCESS error).
I’ve read a few other similar answers, but still don’t have a clear picture of how to fix my code.
Can someone help fix my memory management for the UITableViewCell *cell object in this snippet:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kCityCellReuseID];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCityCellReuseID];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.textLabel.text = [[self.myData objectAtIndex:indexPath.section] valueForKey:kDisplayText];
[cell release];
}
return cell;
}
You have to call
[cell autorelease]instead of[cell release]. When you release the cell there, it gets deallocated immediately before you can return it to the table view and the table view can take ownership of it (i.e., retain it).If you autorelease the cell, you signal that you are giving up ownership of the object (which is the right thing to do since you have created it with
alloc), but it does not get released until the autorelease pool gets to it. By that time, the table view will have retained the cell.If you did not autorelease the cell (i.e. if you deleted the release line), your program would not crash, but it would leak memory every time a new cell is created.