NSAttributedString 冻结 UITableView

5

当使用NSAttributedString时,应用程序在滚动时确实会冻结(当我使用NSString时它工作正常),因此我的解决方法:

- (void)setSubtitleForCell:(TTTableViewCell *)cell item:(TTPhotoPost *)item
{
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:
                                            [item.caption dataUsingEncoding:NSUnicodeStringEncoding]
                                                                            options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                                                 documentAttributes:nil
                                                                              error:nil];

    [cell.descriptionLabel setAttributedText:attributedString];
}

有错误吗?或者有办法使 att.string 更快吗?

NSAttributedString与HTML字符串的转换是非常耗时的。因此,也许通过在后台进行操作,并在主线程中设置attributedText一旦完成(UI相关的事情只能在主线程中完成),可能会更有趣。 - Larme
请查看以下链接 - https://dev59.com/oWIj5IYBdhLWcg3wAwv4 - rishi
2个回答

7

我建议您异步创建NSAttributedString,并从HTML中提取,然后将其存储在您的模型中。这样,当您滚动时,您就不必在每个单元格重用时进行HTML -> attributed string的转换了。


有没有办法在CoreData中存储NSAttributedString? - Zaporozhchenko Oleksandr
@Alexander 我不确定。如果没有,你可以将HTML存储在CoreData中,并将其解析为属性字符串作为一次性操作。 - rounak

0

将其异步化(我认为问题与滚动视图也使用主线程有关):

- (void)setSubtitleForCell:(TTTableViewCell *)cell item:(TTPhotoPost *)item
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:
                                                [item.caption dataUsingEncoding:NSUnicodeStringEncoding]
                                                                                options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                                                     documentAttributes:nil
                                                                                  error:nil];
        dispatch_on_main_queue(^{
            [cell.descriptionLabel setAttributedText:attributedString];
        });
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接