I have a UIButton that is added to each UITableViewCell (except for 2 cells) in a tableview.
The button’s target is the UITableViewController.
I noticed that the app has crashed when the action has been sent to the wrong target. I’m assuming that this is because the target has somehow been deallocated (even though, if the UITableViewController has been deallocated, the buttons should not be visible, and not pressable (and should be deallocated themselves)).
I’m guessing I need to balance the addTarget method, with the removeTarget. Like KVO and retain/release.
But I’m not sure where to do this, because I only have a reference to the button when it is being created and added to the cells, in cellForRowAtIndexPath:?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UIButton *extraButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[extraButton setFrame:CGRectMake(0, 0, 60, 30)];
[extraButton setTitle:@"Meta" forState:UIControlStateNormal];
[extraButton addTarget:self action:@selector(extraButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = extraButton;
}
if (indexPath.row == kNoExtraButtonRow) {
cell.accessoryView.hidden = YES;
} else {
cell.accessoryView.hidden = NO;
}
//set textlabels etc...
return cell;
}
If you have subclassed UIButton for this or have subclassed UITableViewCell then you can put the code in there to remove the target action for the button when the cell or button is deallocated. In the UITableViewCell’s dealloc you can call removeTarget on the its button, or in the button’s dealloc it could call removeTarget for itself.