我使用的表格视图,我重写heightForRowAtIndexPath
。当我运行Xcode的探查,我发现以下几点:iOS - 我的heightForRowAtIndexPath实现导致性能问题,为什么?
我要计算基于一个对象的属性的高度。我对两种对象使用相同的表格视图,User
和Post
。我的实施目前看起来像这样:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text;
Post *cellPost;
User *cellUser;
if (_pageType == FOLLOWERS || _pageType == FOLLOWING) {
cellUser = [self.users objectAtIndex:indexPath.row];
text = cellUser.userDescription.text;
if (text == nil) {
return 70;
}
} else {
cellPost = [self.fetchedResultsController objectAtIndexPath:indexPath];
text = cellPost.text;
}
CGSize boundingSize = CGSizeMake(245, CGFLOAT_MAX);
CGSize requiredSize = [text sizeWithFont:[UIFont fontWithName:@"TisaMobiPro" size:15]
constrainedToSize:boundingSize
lineBreakMode:NSLineBreakByWordWrapping];
CGFloat textHeight = requiredSize.height;
CGFloat cellHeight = textHeight + 40;
if ([cellPost.text isEqualToString:self.post.text]) {
cellHeight += 44;
if (cellHeight < 114) {
cellHeight = 114;
}
} else {
if (cellHeight < 70) {
cellHeight = 70;
}
}
if (cellPost.repostedBy != nil && cellPost.youReposted.boolValue == NO && _pageType != CONVERSATION) {
cellHeight += 27;
}
return cellHeight;
}
如果我删除了大部分代码并且只有return 100
tableView的滚动性能大大提高。您可以发现或提出有关可能导致此性能问题的植入物的建议吗?
盲猜:'[文字sizeWithFont:...]'必须做很多计算。但我甚至没有信心。使用分析器。 – 2014-02-08 17:34:10
您可以先确定字符串的高度并缓存它们吗?这个方法反复运行(如你所见),所以如果大小没有改变(或者很少改变),那么这是非常浪费的。 – Wain
@ H2CO3,是的,当我“禁用”隐藏系统库时,它看起来像字体大小是这里的主要问题。 Wain,会尽力做到这一点。除非你知道更简单更有效的方法,而不是sizeWith字体。 iOS6没有这个问题,现在只有iOS7。 – Anders