我們以前通常會(huì)這樣做
- (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;
}```
嚴(yán)重注意:我們之前這么用都沒(méi)注意過(guò)重用的問(wèn)題,這樣寫(xiě),如果在xib頁(yè)面沒(méi)有設(shè)置 重用字符串的話,是不能夠被重用的,也就是每次都會(huì)重新創(chuàng)建,這是嚴(yán)重浪費(fèi)內(nèi)存的,所以,需要修改啊,一種修改方式是使用如下ios5提供的新方式:
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier
還有就是在xib頁(yè)面設(shè)置好(ios5之前也可以用的)
http://img.blog.csdn.net/20140221142507265
如果忘了在xib中設(shè)置,還有一種方式 http://stackoverflow.com/questions/413993/loading-a-reusable-uitableviewcell-from-a-nib
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;
}
}
還有更常用的
-(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;
}
但是現(xiàn)在有一種新的方式了,可以采用如下的方式
采用registerNib的方式,并且把設(shè)置都放在了willDisplayCell方法中了,而不是以前我們經(jīng)常用的cellForRowAtIndexPath
這個(gè)方法我試了下,如果我們?cè)趚ib中設(shè)置了 Identifier,那么此處的必須一致,否則會(huì)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];
}