Question

I'm doing some text analysis and have run into an annoying performance bump that I can't seem to find how to optimize. I start with the text from a UITextView and split the text into an array of sentences, splitting on characters in ".?!".

Then I loop over each sentence, splitting the sentence into an array of words, and pulling the first and last word from the sentence. With the NSRange of the sentence text in hand, I find the range of the first and last word in the UITextView's text.

The following part is where I get nailed with performance drains. This is how I find the bounding CGRect of the first and last word:

// the from range is increased each iteration 
// so i'm not searching the entirety of the text each pass
NSRange range = [textView.text rangeOfString:firstWord options:kNilOptions range:fromRange];

UITextPosition *beginning = textView.beginningOfDocument;
UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textView positionFromPosition:start offset:range.length];
UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];

firstRect = [textView firstRectForRange:textRange];

I perform this twice, once for the first word and once for the last word.

This works well on smaller text, but approaching 5+ paragraphs Instruments tells me that the UITextView -positionFromPosition: operation is eating up 492ms of clock time, locking up the UI and CPU at 100%.

The thing is I need the CGRect surrounding the first and last words so I can build a CGPath to highlight the sentence. The entire thing works and looks really great, but its the hang while the rects are found that is killing me. I'm fairly new to using UITextView's, so if there is something I can do, either optimizing my searches with ranges or somehow placing my operations on a background thread, I'd be much obliged.

Was it helpful?

Solution

You'll be better off using UITextView's attributedText property, which takes an NSAttributedString. With that, you can set the NSBackgroundColorAttributeName to a colour over a specific range.

Just note the attributed text methods only work in iOS 6+.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top