title: How to protect against substringFromIndex crash?
body: <p>So in my app I get some dynamic text, which I need to extract a certain part of the text out and display it. The part I need from the string can be in a few places. So I wrote this bit of code to handle it: </p>
  
  <pre><code>-(NSString *)getEftPaymentReference
  {
  
      NSRange orderNoteStringRange;
      NSRange endOfRangeForString;
  
      NSString *string;
      NSString *originalString;
  
  
      if (![self.orderPayment.orderPaymentNote hasPrefix:@"ref"]){
  
                  /* Convert the string into plain text */
                  originalString = [[self.orderPayment.orderPaymentNote stringByConvertingHTMLToPlainText] stringByDecodingHTMLEntities];
  
                  /* Get the range before the "at" */
                  orderNoteStringRange = [originalString rangeOfString:@"at"]; // Reference code before  this bit
  
                  /* Create a new string with this range */
                  string = [originalString substringToIndex:orderNoteStringRange.location];
  
                  /* Get the range after "reference" */
                  endOfRangeForString = [string rangeOfString:@"reference" ]; //Reference code after this bit
  
                  /* Returned string now has just the code eg: $FHSR for the reference */
                  string = [string substringFromIndex:endOfRangeForString.location + 10]; //10 added to cover the word "reverence" + white space before the code;
  
      }else {
  
                  /* Convert the string into plain text */
                  originalString = [[self.orderPayment.orderPaymentNote stringByConvertingHTMLToPlainText] stringByDecodingHTMLEntities];
  
                  /* Get the range after "ref." */
                  orderNoteStringRange = [originalString rangeOfString:@"ref."]; // Reference code before  this bit
  
                  /* Create a new string with this range */
                  string = [originalString substringFromIndex:orderNoteStringRange.location + 5];
  
      }
  
      return string;
  }
  </code></pre>
  
  <p>However I am seeing crashes from my users with the following error: </p>
  
  <blockquote>
    <p>** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSCFString substringFromIndex:]: Index 9223372036854775817 out of bounds; string length 46'</p>
  </blockquote>
  
  <p>Now I am not sure why the crash is happening and it doesn't happen often. </p>