【发布时间】:2011-06-03 11:06:59
【问题描述】:
大家好 我有一个 UITableView ,其中包含从 sqllite 获取的项目列表。但是渲染视图时存在内存泄漏。以下是我的 cellForRowAtIndexPath 方法。
static NSString *CellIdentifier = @"BarListItemCell";
BarListItemViewCell *cell = (BarListItemViewCell *)[tableView
dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil) {
NSArray * nib = [[NSBundle mainBundle] loadNibNamed:@"BarListItemViewCell" owner:self options:nil];
for (id cellObject in nib) {
if ([cellObject isKindOfClass : [BarListItemViewCell class]]) {
cell = (BarListItemViewCell *) cellObject;
//break;
}
}
NSString * key = [keys objectAtIndex:[indexPath section]];
NSDictionary * unit = [[barListDataSource objectForKey:key] objectAtIndex:[indexPath row]];
NSLog(@"unit count is %d", [unit retainCount]);
cell.name.text = [unit objectForKey:@"name"];
cell.address.text = [unit objectForKey:@"address1"];
cell.features.text = [unit objectForKey:@"features"];
cell.logo.image = [UIImage imageWithData:[unit objectForKey:@"logo"]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
你可以看到“NSLog(@"unit count is %d", [unit retainCount]);”这一行。很奇怪,viewDidLoad之后,控制台显示3行“unit count is 2”(我全屏有3项)。但是当我拖动屏幕让 UITableView 显示下一个项目时,控制台显示“unit count is 1”。当调用 [tableView reloadData] 方法时,控制台也会显示“unit count is 1”。所以看起来 UITableView 会自动释放数据源。这就是为什么我将单元的内存引用计数保持为2,否则会发生过度释放。但是代价是unit占用的内存永远不会被释放!
【问题讨论】:
标签: iphone uitableview ios memory-leaks