Reputation: 2635
I have this code:
- (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)
}
It's crashing on the sendString method, because of a bad NSRange. I don't understand how this is possible given charactersLeftAfterString is necessarily less than 0 given the condition of the if statement, so charactersAvailableForString is always less than the string length, so how can the range be longer than the string length?
Upvotes: 0
Views: 2958
Reputation: 3312
If your string is empty, i.e [string length] = 0
[string substringWithRange:NSMakeRange(0, charactersAvailableForString)]
will always give a NSRange exception every time, no matter what as
charactersAvailableForString < 0
Also similar problems can arise if [string length] = 5 and charactersLeftAfterString = -12. charactersAvailableForString = 5-12 = -7 [string substringWithRange:NSMakeRange(0, charactersAvailableForString)] will give NsRange Exception.
Upvotes: 2
Reputation: 162712
Have you used the debugger and checked the value of charactersAvailableForString
?
... or printed it?
... or looked at the value when it crashes?
Upvotes: 2