iOS數(shù)據(jù)優(yōu)化之處理HTML字符串
最近項(xiàng)目遇到的問題,因?yàn)楹笈_(tái)返回的數(shù)據(jù)是HTML字符串,所以就按照常規(guī)處理方式把HTML字符串轉(zhuǎn)換成富文本的字符串來處理,事實(shí)證明,tableview會(huì)非??ǎ⑶以斐删€程阻塞,無法響應(yīng)事件
- 在cell的model的set方法中剛開始是這樣操作的~~~~~非???nbsp;
- -(void)setModel:(XAPublicWelfareModel *)model{
- //這就是耗時(shí)操作的代碼
- NSAttributedString * attrStr = [[NSAttributedString alloc]initWithData:[model.content dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
- self.introLabel.attributedText = attrStr;
- }
解決方案1
首先我想到的是把耗時(shí)操作放在子線程來操作
- //1.獲取一個(gè)全局串行隊(duì)列
- dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
- //2.把任務(wù)添加到隊(duì)列中執(zhí)行
- dispatch_async(queue, ^{
- NSAttributedString * attrStr = [[NSAttributedString alloc]initWithData:[model.content dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
- dispatch_async(dispatch_get_main_queue(), ^{
- self.introLabel.attributedText = attrStr;
- });
- });
雖然解決了,卡屏,線程阻塞的問題,但是并沒有解決根本問題,數(shù)據(jù)處理還是很慢,不建議使用
解決方案2
因?yàn)槭莄ell展示,所以只需要展示文本信息就行,那就過濾掉HTML標(biāo)簽,瞬間解決所有問題。所以在列表展示數(shù)據(jù)的時(shí)候HTML轉(zhuǎn)換NSAttributedString一定要慎用
- -(void)setModel:(XAPublicWelfareModel *)model{
- //調(diào)用去除HTML標(biāo)簽的方法,直接賦值。
- self.introLabel.text = [self filterHTML:model.content];
- }
- //去除標(biāo)簽的方法
- -(NSString *)filterHTML:(NSString *)html
- {
- NSScanner * scanner = [NSScanner scannerWithString:html];
- NSString * text = nil;
- while([scanner isAtEnd]==NO)
- {
- [scanner scanUpToString:@"<" intoString:nil];
- [scanner scanUpToString:@">" intoString:&text];
- html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
- //去除空格
- html = [html stringByReplacingOccurrencesOfString:@" " withString:@""];
- }
- return html;
- }
下面簡(jiǎn)單介紹一下NSScanner
NSScanner是一個(gè)類,用于在字符串中掃描指定的字符,翻譯成我們需要的字符串或者數(shù)字,核心就是位置的移動(dòng) 即scanLocation的移動(dòng)變化
在上面的方法中首先指明了要掃描的對(duì)象 html(NSString) NSString * text 很重要 把我們要掃描出來的字符串存到text里面
而這個(gè)掃描到的字符串就是>之前的字符串 scanUpToString這個(gè)方法的意思是將scanLocation停留在>之前 并把之前的字符串傳給text。
回頭來看看我們?nèi)コ齢tml標(biāo)簽的方法 整個(gè)過程都是在掃描過程中進(jìn)行的NSScanner在執(zhí)行scanUpToString這個(gè)方法時(shí)一旦掃描到需要的字符串比如例子中的“<”,其scanLocation就會(huì)變?yōu)閔tml的初始位置。所以,要在執(zhí)行完一次完整的掃描后 把html標(biāo)簽用空字符串替換掉,在進(jìn)行下一次掃描,也就是說再while中 html字符串的標(biāo)簽字符會(huì)越來越少,而每次掃描的初始位置相對(duì)沒有變化都停留在上一次掃描結(jié)束的位置,即"<"標(biāo)簽的前面。