在开发过程中,加载html富文本是非常占用CPU时间的,因为系统需要把一段html富文本是转化成苹果需要的文案颜色、大小之类的。
所以应该注意以下几点:
1、加载html富文本需要做缓存,并且是在拿到数据后,就缓存到数组模型里面
2、不要在cell里面做解析html富文本的操作,滑动会非常卡
3、不要在主线程解析html富文本,可以通过异步并发去解析
以下测试代码:
// 数组数量
let dataCount: Int = 2000
// 创建一个和数组数量一样的数组
var arr: [NSAttributedString] = []
for _ in 0..<dataCount {
// 加入数组中
arr.append(NSAttributedString.init())
}
let group = DispatchGroup.init()
let now = Date()
let dformatter = DateFormatter()
dformatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
dformatter.locale = Locale.init(identifier: "zh_CN")
print("异步开始时间:\(dformatter.string(from: now))")
for i in 0..<dataCount {
let str = "<span><font color=\"#999999\">当日</font> <font color=\"#ffb700\">当前是\(i)</font> <font color=\"#999999\">申请</font></span>"
group.enter()
// 并发异步转html字符串
DispatchQueue.global().async {
let data = str.data(using: String.Encoding.unicode)
let option = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
if let data = data {
let attrStr = try? NSAttributedString(data: data, options:option , documentAttributes: nil)
arr[i] = attrStr!
}
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
let nowEnd = Date()
print("异步结束时间:\(dformatter.string(from: nowEnd))")
}
测试数据:
![](https://img.haomeiwen.com/i2094754/f1ced2653ceefb14.png)
现在用的是2000个item在真机上,同步转换时间是16s,异步是12s
有讲的不对的或者有疑问的可以留言 < /u>
网友评论