NSMakeRange崩溃的应用程序

Pru*_*goe 3 substring nsstring

我正在尝试使用substringWithRange:NSMakeRange获取NSString的子字符串.我从保存的字典中获取初始字符串,保存的字符串写为agent_AGENTNAME,我试图剥离agent_部分.如果我硬编码NSMakeRange中的数字,下面的代码工作正常(如果它是粗糙的话,可以随意批评它) - 就像这样

NSString* savedAgentName =  [NSString stringWithFormat:@"%@", [thisfile substringWithRange:NSMakeRange(6,19)]];
Run Code Online (Sandbox Code Playgroud)

但由于每个人显然都有不同长度的名字,我需要让它更有活力.当我将代码切换到此时:

 NSString* savedAgentName =  [NSString stringWithFormat:@"%@", [thisfile substringWithRange:NSMakeRange(6,[thisfile length])]];
Run Code Online (Sandbox Code Playgroud)

它崩溃了我的应用程序.为什么?

这是更大的代码块:

//get saved agents
 savedAgents = [[NSMutableArray alloc] initWithObjects:@"Select An Agent", nil];
 for(int f=0; f<[rootcontents count]; f++) {
      NSString* thisfile = [NSString stringWithFormat:@"%@", [rootcontents objectAtIndex:f]];
      if ([thisfile rangeOfString:@"agent_"].location != NSNotFound) {

          int thisfilelength = [thisfile length];
          NSString* savedAgentName =  [NSString stringWithFormat:@"%@", [thisfile substringWithRange:NSMakeRange(6,thisfilelength)]];
          //NSLog(@"%@", savedAgentName);

         [savedAgents addObject:savedAgentName];
      } 
 }
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 7

substringWithRange:方法将(如文档所述)提出NSRangeException"如果aRange的任何部分超出接收者的末尾".

通过从thisfile中的第6个位置开始请求thisfilelength字符,您将超过字符串的结尾,从而导致异常.

你需要减少6请求的长度,如下所示:

NSString *savedAgentName = [NSString stringWithFormat:@"%@", 
    [thisfile substringWithRange:NSMakeRange(6,thisfilelength-6)]];
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这段代码可以简化为:

NSString *savedAgentName = 
    [thisfile substringWithRange:NSMakeRange(6,thisfilelength-6)];
Run Code Online (Sandbox Code Playgroud)


但是,由于您希望字符串的其余部分来自某个索引,因此可以通过以下方式进一步简化substringFromIndex::

NSString *savedAgentName = [thisfile substringFromIndex:6];
Run Code Online (Sandbox Code Playgroud)

另请注意,上面的所有代码都假定字符串至少包含6个字符.为安全起见,在获取子字符串之前,请检查此文件的长度是否为6或更大.如果长度少于6个字符,则可以将savedAgentName设置为空白.