项目做直播页面时候,发现一直送礼的时候,动画越来越卡,经过排查,罪魁祸首就是:
NSDictionary *attrs = @{NSFontAttributeName:font};
return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
虽然计算字符串尺寸是系统的方法,但是类似这类计算的方法比较耗性能。如果是平常的滑动浏览的话,是感觉不到的。但是像送礼的时候,伴随列表极快的滚动,CPU的使用率就非常高。
想着只能做个高度缓存来解决了。
为了方便使用,我们将方法添加在tableview的分类里。
先给tableview绑定个dic存放rowHeight的计算结果
- (NSMutableDictionary *)cellHeightDic {
NSMutableDictionary * dic = objc_getAssociatedObject(self, &associateKey);
if(!dic) {
dic = [[NSMutableDictionary alloc] init];
[self setCellHeightDic:dic];
}
return dic;
}
- (void)setCellHeightDic:(NSMutableDictionary *)cellHeightDic {
objc_setAssociatedObject(self, &associateKey, cellHeightDic, OBJC_ASSOCIATION_RETAIN);
}
然后添加方法:
- (float)cacheHeightFromCellIndexPath:(NSIndexPath *)indexPath calculateBlock:(float(^)(void))caculateBlock {
float height = 0;
NSInteger row = indexPath.row;
NSInteger section = indexPath.section;
NSString *key = [NSString stringWithFormat:@"MK_%zd_%zd",section,row]; //key的规则随便弄一下
id object = [self.cellHeightDic objectForKey:key];
if(object) { //有的话
NSLog(@"缓存获取");
height = [object floatValue];
}
else {
NSLog(@"高度计算");
height = caculateBlock();
[self.cellHeightDic setObject:@(height) forKey:key];
}
return height;
}
然后使用的时候:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [tableView cacheHeightFromCellIndexPath:indexPath calculateBlock:^float{
CGFloat height = arc4random() % (100 - 50 + 1) + 50;
return height;
}];
}
就可以了
当然有的时候行高是会发生变化的,记得clean一下就好。
- (void)cleanCacheHeight {
[self.cellHeightDic removeAllObjects];
}