append追加的html中富文本失效,关于加载html富文本耗时的解决方案

在开发过程中,加载html富文本是非常占用CPU时间的,因为系统需要把一段html富文本是转化成苹果需要的文案颜色、大小之类的。

所以应该注意以下几点:

1、加载html富文本需要做缓存,并且是在拿到数据后,就缓存到数组模型里面

2、不要在cell里面做解析html富文本的操作,滑动会非常卡

3、不要在主线程解析html富文本,可以通过异步并发去解析

以下测试代码:

// 数组数量

let dataCount: Int = 2000

// 创建一个和数组数量一样的数组

var arr: [NSAttributedString] = []

for _ in 0..

// 加入数组中

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..

let str = "当日 当前是\(i) 申请"

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))")

}

测试数据:

9417009ab1cb?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

现在用的是2000个item在真机上,同步转换时间是16s,异步是12s

有讲的不对的或者有疑问的可以留言 < /u>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值