iOS - 循环访问单元格并检索数据

Rom*_*mes 4 uitableview viewwillappear ios

对不起,我是iOS开发人员的新手.

我有一个UITableView从单个XiB笔尖拉出单元格的设置.我在笔尖中创建了一个开/关开关,我试图保存开关的状态以获得viewWillDisappear我所拥有的单元格数量.(确切地说是6个细胞).

如何循环遍历所有单元格并保存此信息?

我在我的UIViewController中尝试了这个来获取一个单元格的信息:

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

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

}
Run Code Online (Sandbox Code Playgroud)

它给出了错误"程序接收信号:"EXC_BAD_INSTRUCTION".

我怎么能做到这一点?

Mat*_*uch 11

你必须传递一个有效NSIndexPathcellForRowAtIndexPath:.您使用0,这意味着没有indexPath.

你应该使用这样的东西:

UITableViewCell *tvc = [tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
Run Code Online (Sandbox Code Playgroud)

但是.不要这样做.不要在UITableViewCell中保存状态.
当交换机改变其状态时更新您的dataSource.

如果您已经实现了UITableViewDataSource方法,那么为什么tableView重用单元格.这意味着当细胞重复使用时,细胞的状态将消失.

您的方法可能适用于6个细胞.但它将失败9个细胞.
如果您将第一个单元格滚出屏幕,它甚至可能会失败.


我写了一个快速演示(如果你不在release必要时使用ARC添加)来向你展示你应该如何做到:

- (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]];
}
Run Code Online (Sandbox Code Playgroud)

如你所见,不在单元格中存储状态并不是很复杂:-)