如何防止substringFromIndex崩溃?

时间:2015-03-04 05:32:48

标签: objective-c

所以在我的应用程序中我得到一些动态文本,我需要提取文本的某一部分并显示它。我需要的字符串部分可以在几个地方。所以我写了一些代码来处理它:

-(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;
}

但是我看到我的用户崩溃时出现以下错误:

  

**由于未捕获的异常终止应用程序' NSRangeException',原因:' *** - [__ NSCFString substringFromIndex:]:索引9223372036854775817超出界限;字符串长度46'

现在我不确定崩溃发生的原因并且不会经常发生。

1 个答案:

答案 0 :(得分:1)

明显的虚假价值9223372036854775817NSNotFound + 10.所以,这一部分:

            endOfRangeForString = [string rangeOfString:@"reference" ]; //Reference code after this bit

已返回NSRange字段为location的{​​{1}}。此时字符串NSNotFound不在@"reference"范围内。

您必须始终检查此类方法的结果。不要认为字符串包含您认为的字符串"必须"。

顺便说一句,这类任务是string擅长的事情。