2013-01-15 66 views
0

很奇怪。我預計最後的NSLog打印3,但它不是objectivec - nsrange的計算很奇怪

NSString *value = @"0(234)6"; 

NSRange beginParenthesis = [value rangeOfString:@"("]; 
NSRange endParenthesis = [value rangeOfString:@")"]; 

if (beginParenthesis.location != NSNotFound && endParenthesis.location != NSNotFound) 
{ 
    NSLog(@"%ld", endParenthesis.location); // 5 
    NSLog(@"%ld", beginParenthesis.location + 1); // 2 
    NSLog(@"%ld", endParenthesis.location - beginParenthesis.location + 1); // 5? 
} 

我保存beginParenthesis.location + 1變量...它的工作以及我的預期......爲什麼?

NSRange beginParenthesis = [value rangeOfString:@"("]; 
NSRange endParenthesis = [value rangeOfString:@")"]; 

if (beginParenthesis.location != NSNotFound && endParenthesis.location != NSNotFound) 
{ 
    NSInteger start = beginParenthesis.location + 1; 
    NSLog(@"%ld", endParenthesis.location); //5 
    NSLog(@"%ld", start); // 2 
    NSLog(@"%ld", endParenthesis.location - start); // 3 
} 

這些論點有什麼不同?

回答

2

數學問題:

endParenthesis.location - beginParenthesis.location + 1給出了U(5 - 1 + 1)即等於TO5。 但endParenthesis.location - 開始插上U 5 - 2即3

所以你把這樣的括號:

NSLog(@"%ld", endParenthesis.location - (beginParenthesis.location + 1)); 
+0

謝謝。我很尷尬...... – user1705636

+0

嘿,好吧不要,會發生很多次。寒意:) –