我正在更改UITableViewCellStyleSubtitle的背景,如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
[...]
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"bgCellNormal" ofType:@"png"];
cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:imagePath]] autorelease];
[...]
return cell;
}
我想知道是否有更好的方法可以在不使用这么多分配和自动发布的情况下做到这一点?我的观点是优化这些 uitableview 中的内存!
感谢您的帮助!
赫罗
不应从 tableView:cellForRowAtIndexPath:
访问或设置 backgroundView
属性。框架可能还没有实例化它,它可能会取代你脚下的它。分组和普通表视图在这方面的行为有所不同,任何新的未来样式也是如此。
背景视图应在tableView:willDisplayCell:forRowAtIndexPath:
中设置和/自定义。此方法在首次显示调用之前调用。如果您愿意,您可以使用它完全替换背景。我有用地做这样的事情:
-(void) tableView:(UITableView*)tableView
willDisplayCell:(UITableViewCell*)cell
forRowAtIndexPath:(NSIndexPath*)indexPath;
{
static UIImage* bgImage = nil;
if (bgImage == nil) {
bgImage = [[UIImage imageNamed:@"myimage.png"] retain];
}
cell.backgroundView = [[[UIImageView alloc] initWithImage:bgImage] autorelease];
}
如果您使用 reuseIdentifier 重用单元格,那么您实际上不会分配这么多次内存。
此外,如果您的 png 文件已添加到您的项目中,那么您可以调用 [UIImage imageNamed:@"bgCellNormal.png"。
UIImage 图像命名函数缓存图像以提供优化。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
[...]
UIImageView *bgImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bgCellNormal.png"]];
cell.backgroundView = bgImage;
bgImage release];
[...]
return cell;
}
nib 文件通过继承 UITableView Cell 类来设置单元格的背景图像。
其他明智的,您可以通过以下方式删除自动释放的对象
UIImageView *imageView = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"bgCellNormal.png"];
cell. backgroundView = imageView;
[imageView release];