Search code examples
objective-ciostext-editorcore-textuitextinput

UITextInput - Is it OK to return Incorrect 'beginningOfDocument' & 'endOfDocument'?


I'm creating my own Text Editor in iOS using Core Text. Pretty much everything works great with one exception: Stuff really starts to slow down when the text document is "large". I've discovered that iOS is requesting the entire document text on every change, including selection changes (at least, when I notify the UITextInputDelegate of selection changes). Part of the problem is that I've already optimized my Core Text code by splitting up the document into paragraphs and rendering only the paragraphs that change. But doing this also split up the document string (which is a NSAttributedString) into the separate 'paragraph objects'. So when iOS requests the entire text document, I have to combine all those strings into one string, which takes time and memory.

My solution is to give iOS incorrect UITextPosition's for the beginningOfDocument and endOfDocument methods, limiting those positions to the paragraph(s) intersecting the current selection. This is actually working very well. iOS is now only requesting the current paragraph(s) of the change, which has completely eliminated the slow-down.

So far, so good, but I'm a little worried that this might break something. I've tested this a bit and nothing is broken, but Text Editors can be hard to test (who knows if it'll break in some edge condition).

I have 2 question:

  1. Should iOS be requesting the entire document text on each change? If not, then perhaps some other method in my UITextInput protocol methods that are returning the wrong value, somehow causing iOS to request the entire document.
  2. Does anyone know if this will actually break anything?

Solution

  • Alright, I've been testing this for quite a while now and I've finally found a place where using this technique will break functionality. UITextInput uses beginningOfDocument and endOfDocument to determine whether it has room to "move" when you press the arrow keys on a bluetooth keyboard. Returning only the beginning and end of the currently selected paragraph(s) cause it to ignore the 'arrow' buttons when it is at the beginning or end of that paragraph and those arrows indicate an attempt to move outside what it thinks is the beginning/end of the document. It's easy enough to fix. If the currently selection begins at the beginning/end of a paragraph, I now also return the previous/next paragraph as part of the document, respectively.