App Crashes when I'm trying to assign attributedText to UITextView

libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSTextContentStorage: Inconsistent element cache state. Elements for range {0, 36} are not cached while trying to insert'
terminating with uncaught exception of type NSException

The app crashes with the above warning.

I'm extracting the attributed string from the html, and then assigning it to

textView.attributedText = extractedAttributedString

App, is crashing intermittently. It's working fine for most of the cases. Can someone guide me here?

Thanks!!

If this crash observed on iOS 16 only the easiest thing to try is see if it is TextKit 2 related or not:

let textStorage = NSTextStorage()
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer()
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
let textView = UITextView(frame: ..., textContainer: textContainer)
textView.attributedText = extractedAttributedString

(There's also an easier iOS 16 only way to opt out of TextKit 2)

1 Like
textView.textStorage.beginEditing()
textView.textStorage.setAttributedString(extractedAttributedString)
textView.textStorage.endEditing()

This worked for me!!
The reason why I did it:
A text storage object notifies its layout managers of changes to its characters or attributes, which lets the layout managers redisplay the text as needed. You can access a text storage object from any thread of your app, but your app must guarantee access from only one thread at a time.

Is it safe to use it like this? If not, then I will try your solution.