You must pass a valid NSIndexPath to cellForRowAtIndexPath: You used 0, which means no index.
You should use something like this:
UITableViewCell *tvc = [tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
BUT . Do not do this. Do not save state in UITableViewCell.
Refresh the data source when the switch has changed its state.
If you have implemented the UITableViewDataSource methods, it is correct why your tableView reuses cells. This means that the state of your cells will disappear when the cells are reused.
Your approach can work for 6 cells. But this will not succeed for 9 cells.
It will probably even fail if you scroll the first cell from the screen.
I wrote a small demo (if you are not using ARC add release , where they are needed) to show you how you should do this:
- (void)viewDidLoad { [super viewDidLoad]; self.dataSource = [NSMutableArray arrayWithCapacity:6]; for (NSInteger i = 0; i < 6; i++) { [self.dataSource addObject:[NSNumber numberWithBool:YES]]; } } - (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]; UISwitch *aSwitch = [[UISwitch alloc] init]; [aSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; cell.accessoryView = aSwitch; } UISwitch *aSwitch = (UISwitch *)cell.accessoryView; aSwitch.on = [[self.dataSource objectAtIndex:indexPath.row] boolValue]; return cell; } - (IBAction)switchChanged:(UISwitch *)sender {
since you are not very difficult not to save state in cells :-)
source share