4

申し訳ありませんが、私はiOS開発にかなり慣れていません。

UITableView単一の XiB ニブから引き出されたセルからのセットアップがあります。ペン先にオン/オフ スイッチを作成しましたviewWillDisappear。私が持っているセルの数について、スイッチの状態を保存しようとしています。(正確には6セル)。

すべてのセルをループしてこの情報を保存するにはどうすればよいですか?

UIViewController でこれを試して、1 つのセルの情報を取得しました。

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    UITableView *tv = (UITableView *)self.view;
    UITableViewCell *tvc = [tv cellForRowAtIndexPath:0];

}

「プログラムがシグナルを受信しました:「EXC_BAD_INSTRUCTION」というエラーが表示されます。

どうすればこれを達成できますか?

4

2 に答える 2

11

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]];
}

ご覧のとおり、セルに状態を保存しないことはそれほど複雑ではありません:-)

于 2012-02-13T16:47:36.430 に答える
1

メソッドの最後に移動[super viewDidDisappear:animated];することが、問題に対処する最も適切な方法である可能性があります。それでもうまくいかない場合は、ロジックを に移動しviewWillDisappear:animated:ます。

これに対処するより良い方法は、ビューから現在の状態をまったく読み取らないようにすることです。むしろ、ビューは更新ごとに状態をモデルに渡す必要があります。このようにして、ビューの状態とは完全に独立して、モデルから現在の状態を取得できます。

于 2012-02-13T16:36:17.937 に答える