cell重用

咱们之前一般会这样作ios

- (UITableViewCell  *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     static  NSString  *CellIdentiferId = @"MomentsViewControllerCellID";
     MomentsCell  *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentiferId];
     if (cell == nil) {
        
NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"MomentsCell" owner:nil options:nil];
        cell = [nibs 
lastObject];
        cell.
backgroundColor = [UIColor clearColor];
        

      };
        
     }

     return cell;ide

}ui

严重注意:咱们以前这么用都没注意太重用的问题,这样写,若是在xib页面没有设置 重用字符串的话,是不可以被重用的,也就是每次都会从新建立,这是严重浪费内存的,因此,须要修改啊,一种修改方式是使用以下ios5提供的新方式:spa

- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier
code

还有就是在xib页面设置好(ios5以前也能够用的)内存



若是忘了在xib中设置,还有一种方式  http://stackoverflow.com/questions/413993/loading-a-reusable-uitableviewcell-from-a-nibci

NSArray * nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:nil options:nil];for (id obj in nibObjects){
    if ([obj isKindOfClass:[CustomTableCell class]])
    {        cell = obj;
        [cell setValue:cellId forKey:@"reuseIdentifier"];
        break;
    }

}
字符串

还有更经常使用的get

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{return[self.items count];} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"myCell"];if(!cell){cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];}cell.textLabel.text =[self.items objectAtIndex:indexPath.row];return cell;

}
it


可是如今有一种新的方式了,能够采用以下的方式

采用registerNib的方式,而且把设置都放在了willDisplayCell方法中了,而不是之前咱们常常用的cellForRowAtIndexPath

这个方法我试了下,若是咱们在xib中设置了 Identifier,那么此处的必须一致,不然会crash的
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    MyCustomCell * cell = [tableView dequeueReusableCellWithIdentifier:
@"myCell"];
    
if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:
@"MyCustomCell" bundle:nil] forCellReuseIdentifier:@"myCell"];
        cell = [tableView dequeueReusableCellWithIdentifier:
@"myCell"];
    }
    
    
return cell;
}

- (
void)tableView:(UITableView *)tableView willDisplayCell:(MyCustomCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.leftLabel.text = [
self.items objectAtIndex:indexPath.row];
    cell.rightLabel.text = [
self.items objectAtIndex:indexPath.row];
    cell.middleLabel.text = [
self.items objectAtIndex:indexPath.row];}

相关文章
相关标签/搜索