As mentioned in my comment, it's not a garbage range value, it's a representation for NSNotFound
. This means there isn't any occurrence of whitespace or newlines in the string you have passed it (which is a valid case). As such, we need to prepare for that.
Based on your code, I have changed it to check for NSNotFound
. Also, there was no need to subtract 1 from the finalRange length. When I tested this code sample, that cropped the last character from my URL string. Comments have been added to the end of changed/queried lines.
NSString *urlString = @""; // Is this being used?
NSRange startRange = [self rangeOfString:@"http://" options:NSCaseInsensitiveSearch];
if (startRange.length) {
NSString *subStr = [self substringFromIndex:startRange.location];
NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSRange endRange = [subStr rangeOfCharacterFromSet:set];
if (endRange.location == NSNotFound) { // Check for NSNotFound
debugTrace(@"finalString : %@", subStr);
}
else if (endRange.length) {
NSRange finalRange;
finalRange.location = startRange.location;
finalRange.length = endRange.location; // No need to subtract 1
NSString *finalString = [self substringWithRange:finalRange];
debugTrace(@"finalString : %@", finalString);
}
}
return urlString;
I have tested this briefly, and it seems to work.