UITextView stuck in memory after link preview

I noticed that UITextViews get stuck in memory after a preview has been shown. I mean the preview you get when you long press a url.

For this to work editable should be false and dataDetectorTypes should include .link. Include a url to the text and long press it. A preview should show. When you quit the preview and you remove the text view with removeFromSuperView() (or just close the ViewController containing the text view), it won't deinit anymore. You can check by overriding deinit or by checking if a weak reference (like IBOutlet) has become nil.

I also noticed that two system ViewControllers stay in memory too, namely SFSafariViewController and SFBrowserRemoteViewController. I don't know if this is by design.

Tried on iOS 16.2 and 16.3.1.

iOS 17 still has the same issue but at least now there is a way to avoid it:

The leak will clear once you set isSelectable to false. So I'd advice to do this before removeFromSuperview() or in VC's deinit.

myTextView.isSelectable = false
myTextView.removeFromSuperview()
//in ViewController
deinit {
    myTextView.isSelectable = false
}

Or even better is to just subclass UITextView and override removeFromSuperview():

//in UITextView subclass
override func removeFromSuperview() {
    let wasSelectable = isSelectable
    isSelectable = false
    super.removeFromSuperview()
    isSelectable = wasSelectable
}

Even setting isSelectable directly back to true the next line will work (at least in debug builds). This way the links still work if you decide to reuse the view.

UITextView stuck in memory after link preview
 
 
Q