2011-05-04 34 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,因为你从来没有公布过它。

相关问题