NSIndexPath
に有効なものを渡す必要がありますcellForRowAtIndexPath:
。0を使用しました。これは、indexPathがないことを意味します。
次のようなものを使用する必要があります。
UITableViewCell *tvc = [tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
しかし。これをしないでください。UITableViewCellに状態を保存しないでください。
スイッチの状態が変更されたときにdataSourceを更新します。
UITableViewDataSourceメソッドを実装している場合、tableViewがセルを再利用する理由は正しいです。つまり、セルを再利用すると、セルの状態が消えます。
あなたのアプローチは6つのセルで機能するかもしれません。ただし、9セルでは失敗します。
最初のセルを画面外にスクロールすると、おそらく失敗するでしょう。
release
代わりにどのように行うべきかを示すために、簡単なデモを作成しました(必要な場所でARC addを使用しない場合)。
- (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];
/* configure cell */
return cell;
}
- (IBAction)switchChanged:(UISwitch *)sender
{
// UITableViewCell *cell = (UITableViewCell *)[sender superview];
// NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
CGPoint senderOriginInTableView = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:senderOriginInTableView];
[self.dataSource replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:sender.on]];
}
ご覧のとおり、セルに状態を保存しないことはそれほど複雑ではありません:-)