一开始写tableView的时候我每一个Cell都加到了tableView的视图上去了,这样十分浪费内存。其实可以只创建若干个Cell,当其中的部分Cell滑出Device的界面时它就闲置了,当加载下一个cell时可以把这些闲置的cell复用,要注意的是复用时先前的cell的一些状态都是在的。
下面是我写的添加cell的代理方法,这种方法对内存消耗就很大了,因为没有
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.text = [self.arr[indexPath.section] objectAtIndex:indexPath.row];
return cell;
}
所以要用缓存池来解决这个问题,先静态设置一个NSString 类型的identifier标志Cell,在缓存池中找有没空闲的cell如果有就直接把该Cell拿来重新赋值,否则创建一个cell。
static NSString *identifier = @"myCell";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = [self.arr[indexPath.section] objectAtIndex:indexPath.row];
return cell;
}
如果是用nib文件自定义cell的话复用代码如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"myCell";
PCDownLoadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"PCDownLoadTableViewCell" owner:nil options:nil];
cell = nibs.lastObject;
}
return cell;
}