NSString substringWithRange崩溃

时间:2011-07-26 17:23:47

标签: iphone objective-c nsstring

我有这段代码:

- (void)splitAndSendString:(NSString *)string
             withAlignment:(UITextAlignment)alignment
         verticalExpansion:(NSUInteger)verticalExpansion
       horizontalExpansion:(NSUInteger)horizontalExpansion
                     inRed:(BOOL)isRed
          leftBumperString:(NSString *)leftString
         rightBumperString:(NSString *)rightString
                lineLength:(NSUInteger)lineLength
{
    NSInteger charactersLeftAfterString = lineLength - [string length] -
            [leftString length] - [rightString length];

   // if either of the bumpers is nil, then replace it with @""
   //so that we don't get "null" printed
   if (leftString == nil)  { leftString = @"";     }
   if (rightString == nil) { rightString = @"";    }

   if (charactersLeftAfterString < 0) {
        NSInteger charactersAvailableForString =
           [string length] + charactersLeftAfterString;
        [self sendString:[NSString stringWithFormat:@"%@%@%@", leftString, [string substringWithRange:NSMakeRange(0, charactersAvailableForString)], rightString] withAlignment:UITextAlignmentLeft verticalExpansion:verticalExpansion horizontalExpansion:horizontalExpansion inRed:isRed];
   }
   //(a lot of other code here that isn't relevant)
}

由于NSRange错误,它在sendString方法上崩溃了。我不明白如果给定if语句的条件,由于charactersLeftAfterString必须小于0,所以这是可能的,所以charactersAvailableForString总是小于字符串长度,那么范围如何比字符串长度长?

2 个答案:

答案 0 :(得分:2)

您是否使用过调试器并检查了charactersAvailableForString

的值

......还是打印出来的?

...或者看崩溃时的值?

答案 1 :(得分:1)

如果你的字符串是空的,即[string length] = 0

[string substringWithRange:NSMakeRange(0,charactersAvailableForString)]

每次都会给出一个NSRange异常,无论是什么

charactersAvailableForString&lt; 0

如果[string length] = 5且charactersLeftAfterString = -12,也会出现类似的问题。 charactersAvailableForString = 5-12 = -7 [string substringWithRange:NSMakeRange(0,charactersAvailableForString)]将给出NsRange异常。