Ios 如何提高NSTextStorage addAttribute性能

Ios 如何提高NSTextStorage addAttribute性能,ios,swift,textkit,nstextstorage,Ios,Swift,Textkit,Nstextstorage,我在NSTextStorage中有一个很长的文本(可能是像>200页这样的常见书籍)。 我通过以下方式为textContainers分发此文本: let textStorageLength = defaultTextStorage?.length ?? 0 while layoutManager!.textContainer(forGlyphAt: textStorageLength - 1, effectiveRange:

我在
NSTextStorage
中有一个很长的文本(可能是像>200页这样的常见书籍)。 我通过以下方式为textContainers分发此文本:

let textStorageLength = defaultTextStorage?.length ?? 0
while layoutManager!.textContainer(forGlyphAt: textStorageLength - 1, 
                                   effectiveRange: nil) == nil {
  let textContainer = NSTextContainer(size: textContainerSize)
  layoutManager!.addTextContainer(textContainer)
  pagesCount += 1
}
然后,我在pageViewController上使用这些容器进行文本视图

我有一些词,比如:

func selectTappableWordsFromList(_ list: [PositionWithWord]) {
  self.defaultTextStorage?.beginEditing()

  list.forEach {
    if !self.shouldInterruptCurrentProcesses {
      self.markWordInDefaultTextStorage(positionWithWord: $0)
    } else {
      self.shouldInterruptCurrentProcesses = false
      self.defaultTextStorage?.endEditing()

      return
    }
  }

  self.defaultTextStorage?.endEditing()
}


 func markWordInDefaultTextStorage(positionWithWord: PositionWithWord) {
    let range = NSMakeRange(positionWithWord.position!.start, 
                            positionWithWord.position!.length)

    defaultTextStorage?.addAttributes(defaultAttributes, range: range)
 }

 let defaultAttributes: [NSAttributedStringKey: Any] = [
    .underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
    .underlineColor: UIColor.BookReader.underline
 ] 
问题在于:在全文存储中标记单词的速度非常慢。书中的页数越多,它的速度就越慢

还提供了探查器中cpu使用情况的屏幕截图


有改进逻辑的方法吗

@matt我已经知道了have@matt抱歉,更新了question@matt我真的很感激你的帮助,因为实际上我没有更多的想法。我已经尽可能地优化了它