我知道这种问题以前已经问过很多次了。但是我很困惑,即使经过大量搜索也没有找到任何解决方案。
我有一张表格,其中每6个单元格之后便有一个单元格在重复。.但很奇怪的是,如果单击任何重复的单元格,它会向我显示正确的数据,该数据应该在didSelectRowAtIndexpath方法中显示。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UIImageView * cellImageView;
NSArray *pathComponents;
NSData *imageData;
UIImage *image;
UILabel * mainLabel = nil;
UITableViewCell *cell = nil;
static NSString *CellIdentifier = @"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSLog(@"in loop");
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease];
mainLabel = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 220, 15)]autorelease];
[cell addSubview:mainLabel];
}
mainLabel.backgroundColor = [UIColor clearColor];
mainLabel.textColor = [UIColor redColor];
mainLabel.numberOfLines = 0;
mainLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:11];
mainLabel.lineBreakMode = NSLineBreakByWordWrapping;
mainLabel.text = [[array objectAtIndex:indexPath.row]retain];
return cell;
}
最佳答案
if (cell == nil)
{
NSLog(@"in loop");
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease];
mainLabel = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 220, 15)]autorelease];
mainLabel.tag = 1234;
[cell addSubview:mainLabel];
}
else {
mainLabel = (UILabel*)[cell viewWithTag:1234];
}
但是除了回收本身的问题外,还有其他一些问题。为了获得最佳性能,标签的所有设置(每次操作都相同)应在
if
子句内完成。仅在if / else之后的方法主体中设置变量文本。此外,如果不使用ARC,则应在addSubview调用之后和
if
子句末之前释放标签。并且标签文本不应该保留,因为它是从
array
获取的-标签将保留它。