ios - UITableView 中的二进制数据导致高 CPU 负载和卡住

标签 ios objective-c uitableview core-data binary-data

我有一些 HTML 数据,我将其作为 Binary Data 存储在 CoreData 中。我在 UITableViewCells 中将其显示为 NSMutableAttributedString,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSManagedObject *row = [self.messagesFRC objectAtIndexPath:indexPath];

    MessageLTableViewCell *cell = (MessageLTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:@"MSGCELLID" forIndexPath:indexPath];

    NSString *messageText = [[NSString alloc] initWithData:[row valueForKey:@"message_text"] encoding:NSUTF8StringEncoding];

    messageText = [NSString stringWithFormat:@"<style>body{font-family: '%@';direction:rtl;float:right; font-size:%fpx;}</style>%@", FONT_TEXT, 17.0, messageText];

    NSError *err = nil;
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]
      initWithData:[messageText dataUsingEncoding:NSUTF8StringEncoding]
      options:
      @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
        NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding),
    }
    documentAttributes: nil
    error: &err];


    if(err)
        NSLog(@"Unable to parse label text: %@", err);
    cell.messageText.attributedText = attrStr;


    return cell;

}

问题在于它会导致高 CPU 负载,并且 UITableView 在滚动时会卡住。以最佳性能处理它的最佳实践解决方案是什么?

最佳答案

首先,您应该在托管对象子类中包含此逻辑。这种数据操作的繁重工作不属于 TableView 数据源。为此,为您的托管对象子类提供一个方便的方法 attributedString

其次,您可以将 HTML 存储为文本,即 String 类型。这将具有额外的优势,即它将变得可搜索。

说到性能,似乎NSHTMLTextDocumentType的数据方法确实非常慢(有人在评论中提到了一个测试 here )。另一种方法是使用 NSRange,如果 HTML 字符串不太复杂,这是可行的。

关于ios - UITableView 中的二进制数据导致高 CPU 负载和卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251546/

相关文章:

ios - 共享扩展 loadItemForTypeIdentifier 为 NSURL 返回错误

ios - 如何仅在关闭特定 UIViewController 时才执行操作?

objective-c - 两个相同选项卡 View 中的 UITableView 表现不同

ios - 在 UITableViewController 中使用 UITextView - 点击外部以关闭键盘

SWIFT 属性列表 : From TableView to DetailView plist

ios - 通过访问 AppDelegate 中的 Tab Bar Items 更改 Tab Bar Item Image inset

ios - UiTextView - 仅添加一行时的位置

ios - 将多上下文 CoreData 应用于基于 NSOperationQueue 的应用程序

ios - 为什么我无法从网络服务获取数据,我得到反馈“列表不存在”。

ios - 在 iOS 中显示多列表格的最有效方法是什么?