遍历UITableView的UITableViewCells [英] Looping through UITableViewCells of a UITableView

查看:52
本文介绍了遍历UITableView的UITableViewCells的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在尝试从UITableView加载单元格,并将其放入NSMutableArray中,以便稍后进行迭代.我有一个称为populateArrayWithCells的方法,在我放入6个以上的单元格之前,它可以正常工作.由于某种原因,返回的对象为nil.我的代码在下面,StocksAndAccounts是UITableView,并且在第1节中将UITableViewCells进行了子类化.

So I've been trying to load cells from a UITableView and put those into an NSMutableArray to be iterated through later. I have a method called populateArrayWithCells which works fine until I put in more than 6 cells. For some reason the object returned is nil. My code is below, StocksAndAccounts is the UITableView and I have subclassed the UITableViewCells in section 1.

- (void) populateArrayWithCells
{
for (int i = 0; i < [StocksAndAccounts numberOfRowsInSection:1]; i++) {
    if ([StocksAndAccounts cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:1]] == nil) {
        NSLog(@"object at index %i is nil", i);
    }
    [stocksCells addObject:[StocksAndAccounts cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:1]]];
}
}

通过IBAction调用时,此函数成功返回单元格,直到索引为6,在这种情况下,该值为nil并由于试图添加一个nil的对象而崩溃.任何解决此问题的帮助将不胜感激.

This function, when called through an IBAction, returns the cell successfuly until the index is 6, in which case it is nil and crashes because it's trying to add an object that is nil. Any help with this problem would be greatly appreciated.

推荐答案

我认为您误解了UITableViews的工作原理.表格视图中的单元格仅在需要显示时才加载,并且会被回收,因此,如果您一次只能在屏幕上看到六个单元格,则该表格将仅包含六个单元格,并且将保持更新和重复使用上下滚动的那六个.

I think you've misunderstood how UITableViews work. The cells in a tableview are only loaded when they need to be displayed, and they are recycled, so if you can only see six cells on screen at a time then the table will only ever contain six cells and it will just keep updating and reusing those same six as you scroll up and down.

与其将数据存储在表单元格中,不如将其存储在视图控制器中的自定义对象数组中,并在表从数据源方法请求它们时使用这些对象填充单元格.

Instead of storing data in your table cells, store it in an array of custom objects in your view controller and use those objects to populate the cells when the table requests them from your datasource methods.

这样,如果您需要将数据用于表中显示之外的其他内容,则可以从原始对象重新创建它,而不必尝试将其复制到表单元格之外.

That way if you ever need to use that data for something other than displaying in the table, you can re-create it from the original object instead of trying to copy it out of the table cell.

这篇关于遍历UITableView的UITableViewCells的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆