NSMakeRange crashing app

I am trying to get the substring NSString using substringWithRange: NSMakeRange. I get the original string from the saved dictionary, the saved string is written as agent_AGENTNAME, I'm trying to delete the agent_ part. The code below works fine (feel free to criticize it if it's rude) if I hardcode the numbers for NSMakeRange - for example,

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

but since everyone will obviously have names of different lengths, I need to make this more dynamic. When I switch the code to this:

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

he resets my application. What for?

Here's more code snippet:

//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];
      } 
 }

Thank.

+3
source share
1 answer

substringWithRange: ( ) NSRangeException ", - aRange ".

, , , .

, 6 :

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

, :

NSString *savedAgentName = 
    [thisfile substringWithRange:NSMakeRange(6,thisfilelength-6)];


, , , , substringFromIndex::

NSString *savedAgentName = [thisfile substringFromIndex:6];

, , 6 . , , 6 , . 6 , _ .

+7

Source: https://habr.com/ru/post/1788091/


All Articles