iOS – 循环单元格并检索数据

对不起,我很新的iOS开发。

我从单个XiB笔尖拉出的单元格中有一个UITableView安装程序。 我已经在笔尖上创build了一个开/关开关,并且我试图在viewWillDisappear保存开关的状态,以获得所拥有的单元的数量。 (6个细胞是确切的)。

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

我在我的UIViewController中试图获取一个单元格的信息:

 - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; UITableView *tv = (UITableView *)self.view; UITableViewCell *tvc = [tv cellForRowAtIndexPath:0]; } 

它给了我错误“编程接收到的信号:”EXC_BAD_INSTRUCTION“。

我怎样才能做到这一点?

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

你应该使用这样的东西:

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

但是 。 不要这样做。 不要在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]]; } 

正如你所看到的那样,在单元中不存储状态并不复杂:-)

移动[super viewDidDisappear:animated]; 到您的方法结束可能是解决问题的最方便的方法。 如果这不起作用,将逻辑移入viewWillDisappear:animated:

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