繁体   English   中英

使用 NSRange 的问题:索引超出范围

[英]Problem using NSRange: Index out of bounds

我试图在我的字符串中检测网站 URL,然后做一些属性字符串的东西,比如加粗等。

我的正则表达式定义为:

static NSRegularExpression *websiteRegularExpression;
static inline NSRegularExpression * WebsiteRegularExpression() {
    if (!websiteRegularExpression) {
        websiteRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|]" 
                                                                        options:NSRegularExpressionCaseInsensitive 
                                                                          error:nil];
    }

    return websiteRegularExpression;
}

这是我列举的地方:

 -(void)setBodyText
    {
        __block NSRegularExpression *regexp = nil;    
        bodyLabel.delegate = self;
        [self.bodyLabel setText:@"http://www.google.com" afterInheritingLabelAttributesAndConfiguringWithBlock:^NSAttributedString *(NSMutableAttributedString *mutableAttributedString) {

            NSRange stringRange = NSMakeRange(0, [mutableAttributedString length]);

            regexp = WebsiteRegularExpression ();
            NSRange nameRange = [regexp rangeOfFirstMatchInString:[mutableAttributedString string] options:0 range:stringRange];
            UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:18.0]; 
            CTFontRef boldFont = CTFontCreateWithName((CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
            if (boldFont) {
                [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)boldFont range:nameRange];
                CFRelease(boldFont);
            }

            [mutableAttributedString replaceCharactersInRange:nameRange withString:[[[mutableAttributedString string] substringWithRange:nameRange] uppercaseString]];
            return mutableAttributedString;
        }];

        regexp = WebsiteRegularExpression();
        NSRange linkRange = [regexp rangeOfFirstMatchInString:self.bodyLabel.text options:0 range:NSMakeRange(0, [bodyLabel.text length])];
        [self.bodyLabel addLinkToURL:nil withRange:linkRange];
    }

我得到错误:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFString substringWithRange:]: Range or index out of bounds'

我该如何解决?

在调用substringWithRange之前检查nameRange的内容。 如果您的正则表达式不匹配,则rangeOfFirstMatchInString的返回值将是

{NSNotFound, 0}

NSNotFound被定义为NSIntegerMax所以你可以想象为什么这个值可能超出你的mutableAttributedString的范围。

更新评论

所以要检查substringWithRange的结果:

if (nameRange.location == NSNotFound)
    // didn't match the WebsiteRegularExpression() do something else

您没有在任何地方检查您返回的任何范围是否具有 range.location = NSNotFound。 您的一场比赛是空的,然后您正试图将该范围用于其他事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM