Hello there i found an issue on my app that is maybe not critical but strange.
I have in my viewController a switch, let's call it theSwitch, when I populate the cells, on indexPath (0,0) i put that switch as the accessory view.
The title of the cell changes depending of the state of the switch
//Code simplified for simplicity
if(indexPath.section == 0 && indexPath.row == 0) {
cell.textLabel.text = self.filtersActivatedSwitch.on ? NSLocalizedString(@"Filters activated", nil) : NSLocalizedString(@"Filters deactivated", nil);
cell.accessoryView = self.filtersActivatedSwitch;
}
When the switch is pressed this method is called
-(void)switchActivated {
[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:VisibilityFilterTableViewSectionMasterFilter]];
}
This will create a deadlock because on the method cellForRowAtIndexPath when i try to dequeue the cell it will create a new one instead (this is tested, i thought it made more sense that it used the same cell that i wanted to reload) and in the configuration of the cell the switch will be added as accessoryView...
This is where it gets tricky...
BadPirate's answer explain when layoutSubview is called on a tableviewcell
When is layoutSubviews called?
-addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target
I think the same should happen with removeFromSupperview (supposition), so the new cell has the layoutSubview called.. it checks the accessoryView, see that it is not nil so it add it ass subview, on the other hand in the old cell (that did not get dequeued for any reason so i couldn't clear the accessoryView) layoutSubviews gets called because of the removeFromSuperview (again supposition) it checks that the accessoryView is not nil, it adds the switch as subview... and repeat eternally.
My question is... why won't the table view use the already dequeued cell? the fact that two tableviewcells have the same accessoryView clearly will crash my app.
Or i'm ussing the accessory Views wrong?
Cheers!
EDIT: Here is the code on prepareForReuse
- (void)prepareForReuse {
[super prepareForReuse];
for (UIView *view in self.contentView.subviews) {
[view removeFromSuperview];
}
for (UIView *view in self.imageView.subviews) {
[view removeFromSuperview];
}
self.textLabel.text = nil;
self.detailTextLabel.text = nil;
self.imageView.image = nil;
self.imageView.tag = 0;
self.accessoryView = nil;
}