2011-06-29 32 views
3

我想檢測網站的網址在我的字符串,然後做一些屬性字符串的東西一樣粗體就等問題使用NSRange:索引出界

我的正則表達式定義爲:

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' 

我該如何解決?

+0

你可以發佈你正在使用正則表達式?具體是什麼是mutableAttributedString。我的猜測在這一行中是錯誤的。 [mutableAttributedString string] substringWithRange:nameRange] uppercaseString]];您可能需要通過確保每個步驟都讓您滿意,進行調試。 – madmik3

+0

我相信你是對的。我用正則表達式更新了我的代碼。仍然不知道如何解決... –

回答

8

檢查名稱範圍的內容,然後再致電substringWithRange。如果你的正則表達式不匹配,那麼對於rangeOfFirstMatchInString返回值將是

{NSNotFound, 0}

NSNotFound被定義爲NSIntegerMax所以你可以想象爲什麼這值可能超出範圍的mutableAttributedString

更新評論

所以檢查substringWithRange結果:

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

我該如何檢查nameRange的內容? –

+0

@ sheehan-alam只需檢查範圍對象上的位置成員(請參閱更新)。 – RedBlueThing

4

無處檢查是否有任何範圍你有回到range.location = NSNotFound。其中一場比賽是空的,然後你正在嘗試使用該範圍來處理其他事情。

+0

我對NSRange很新,你能告訴我一個如何在我的代碼中執行這個檢查的例子嗎? –

+2

由於RedBlue打敗了我的迴應,我剛剛投了他的答案。 –

+0

helmstetter-gelner乾杯;) – RedBlueThing