此方法被调用多次
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
1.
写为静态局部变量 避免上述方法被多次调用 导致内存多次分配空间 从而耗费性能
static NSString *ID = @"cell";
若需要cell时 首先要从缓存池中查看是否有ID标识的cell 若有则直拿出使用 若无 则创建cell并绑定标识ID
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
此代码块执行次数有限 所以有关cell设置一样的代码可放置在{}中(比如 cell的背景颜色)
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
2.注册法(常用于自定义cell)
static NSString *ID = @"cell";
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
此行代码执行后 cell已有值 原理:执行此行代码时 先去缓存池中查看是否有ID标识的cell可重用 若有拿出使用 若无判断是否有注册过ID标识的cell,若有则系统会自动创建UITableViewCell并绑定标识ID
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];