2011-05-04 33 views
1

嗨這裏是我的功能,但每當我嘗試初始化和分配foo它下降,你能告訴我爲什麼嗎?爲什麼代碼落在substringwithrange範圍

-(NSString*)modifyTheCode:(NSString*) theCode{ 
     if ([[theCode substringToIndex:1]isEqualToString:@"0"]) { 
      if ([theCode length] == 1) { 
      return @"0000000000"; 
     } 
      NSString* foo = [[NSString alloc]initWithString:[theCode substringWithRange:NSMakeRange(2, [theCode length]-1)]]; 

      return [self modifyTheCode:foo]; 

     } else { 

      return theCode; 

     } 


} 

錯誤消息:

warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.2 (8H7)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found). 

回答

1

這一行

NSString* foo = [[NSString alloc]initWithString:[theCode substringWithRange:NSMakeRange(1, [theCode length]-1)]]; 

,並嘗試替換該行

NSString* foo = [[NSString alloc]initWithString:[theCode substringWithRange:NSMakeRange(2, [theCode length]-1)]]; 

..

+0

它會刪除第一個或最後一個字符嗎?例如它應該爲這個字符串「0abba」添加什麼? – Csabi 2011-05-04 10:30:34

+0

nope..index從0開始。假設你有一個5個字符的字符串,所以範圍索引爲0到4,substringWithRange應該從索引1到4獲得字符串,right ... – Krishnabhadra 2011-05-04 10:33:12

+0

如果你從索引2開始並給[字符串長度] - 1,您要求從索引2獲得4個字符,這應該是2,3,4,5 .. – Krishnabhadra 2011-05-04 10:34:04

1

什麼是錯誤訊息? 如果您正在使用NSRange,也許您應該首先檢查代碼的長度。

+0

它甚至在長度爲10個字符時第一次下降 – Csabi 2011-05-04 10:25:29

1

因爲範圍是無效的。 NSRange有兩個成員,位置和長度。您給出的範圍從字符串的第三個字符開始,並且字符串的長度減1。所以你的長度比字符串中剩下的字符長一個字符。

假設代碼爲@"0123"。您創建的範圍是{ .location = 2, .length = 3 }這代表:


^start of range is here 
    ^start of range + 3 off the end of the string. 

順便問一下,你會很高興地知道,有方便的方法,所以你不必與範圍的混亂。你可以這樣做:

if ([theCode hasPrefix: @"0"]) 
{ 

    NSString* foo = [theCode substringFromIndex: 1]; // assumes you just want to strip off the leading @"0" 

    return [self modifyTheCode:foo]; 

} else { 

    return theCode; 

} 

順便說一句,你的原代碼泄露foo,因爲你從來沒有公佈過它。

相關問題