UITableView的重用机制
UITableView通过重用单元格来达到节省内存的目的:通过为每个单元格指定一个重用标识符(reuseIdentifier),即指定了单元格的种类,以及当单元格滚出屏幕时,允许恢复单元格以便重用.对于不同种类的单元格使用不同的ID,对于简单的表格,一个标识符就够了.
假如一个TableView中有20个单元格,但是屏幕上最多能显示12个,那么实际上iPhone只是为其分配了12个单元格的内存,没有分配20个,当滚动单元格时,屏幕内显示的单元格重复使用这12个内存,以下代码用于测试内存
#import "ViewController.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
UITableView* table;
int count;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
table=[[UITableViewalloc]initWithFrame:self.view.framestyle:(UITableViewStylePlain)];
table.delegate=self;
table.dataSource=self;
[self.viewaddSubview:table];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 20;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString* cellid=@"cell";
UITableViewCell* cell=[tableViewdequeueReusableCellWithIdentifier:cellid];
if (cell==nil) {
cell=[[UITableViewCellalloc]initWithStyle:(UITableViewCellStyleSubtitle)reuseIdentifier:cellid];
cell.detailTextLabel.text=[NSStringstringWithFormat:@"%d",++count];
}
cell.textLabel.text=[NSStringstringWithFormat:@"%d",indexPath.row];
return cell;
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end