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

时间:2012-02-13 16:33:38

标签: ios uitableview viewwillappear

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

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

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

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

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

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

}

它给出了错误“程序接收信号:”EXC_BAD_INSTRUCTION“。

我该如何做到这一点?

2 个答案:

答案 0 :(得分:11)

您必须将有效的NSIndexPath传递给cellForRowAtIndexPath:。您使用0,这意味着没有indexPath。

你应该使用这样的东西:

UITableViewCell *tvc = [tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

<强> BUT 即可。不要这样做。 不要在UITableViewCell中保存状态。
当交换机改变状态时更新你的dataSource。

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

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


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

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

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

答案 1 :(得分:1)

[super viewDidDisappear:animated];移到方法的末尾可能是解决问题的最有效方法。如果这不起作用,请将逻辑移至viewWillDisappear:animated:

处理此问题的更好方法是避免从视图中读取当前状态。相反,视图应该在每次更新时将状态传递给模型。这样,您就可以从模型中获取当前状态,完全独立于视图的状态。

相关问题