title: Truncate an NSString to width
body: <p>I'm trying to convert the <a href="http://mobiledevelopertips.com/cocoa/truncate-an-nsstring-and-append-an-ellipsis-respecting-the-font-size.html" rel="noreferrer">code found here</a> to a binary algorithm instead, since the linear method is terribly slow. I have a working implementation, but theres seems to be some thing I'm missing, since the results I'm getting are not precise (that is, if I add or subtract 20 or so pixels from the width, I get the same truncated string..it should be a little more accurate and have a closer cut):</p>
  
  <pre><code>-(NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont*)font addQuotes:(BOOL)addQuotes
  {
      int min = 0, max = self.length, mid;
      while (min &lt; max) {
          mid = (min+max)/2;
  
          NSString *currentString = [self substringWithRange:NSMakeRange(min, mid - min)];
          CGSize currentSize = [currentString sizeWithFont:font];
  
          if (currentSize.width &lt; width){
              min = mid + 1;
          } else if (currentSize.width &gt; width) {
              max = mid - 1;
          } else {
              min = mid;
              break;
          }
      }
      return [self substringWithRange:NSMakeRange(0, min)];
  }
  </code></pre>
  
  <p>Can anyone see off the bat what could be wrong with that? (This is a category method, so <code>self</code> is an NSString.</p>