Note that there are some explanatory texts on larger screens.

plurals
  1. POObjective-c Substring Range Exception
    text
    copied!<p>I am creating an imap client. I want to parse body and header of incoming data but it crashes. I couldn't understand why it crashes and gives substring out of range error. How can I fix it?</p> <p>I only want to check if the incoming string contains "FETCH" so I parse data, since string comes like * FETCH or * 1 FETCH I thought checking isEqualToString range of (4,6) would be enough but that didn't work.</p> <pre><code>- (NSString*) readLine { NSMutableData* data = [[NSMutableData alloc] init]; unsigned char c; for (;;) { recv(socket_, &amp;c, sizeof(c), 0); if (c == '\n') { NSString* s = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSString *str = [s substringWithRange:NSMakeRange(4, 6)]; if( [str isEqualToString:@"FETCH "]){ NSMutableArray *substrings = [NSMutableArray new]; NSScanner *scanner = [NSScanner scannerWithString:s]; [scanner scanUpToString:@"}" intoString:nil]; while(![scanner isAtEnd]) { NSString *substring = nil; [scanner scanString:@"}" intoString:nil]; if([scanner scanUpToString:@"*" intoString:&amp;substring]) { // If the space immediately followed the }, this will be skipped [substrings addObject:substring]; } [scanner scanUpToString:@"}" intoString:nil]; // Scan all characters before next } } NSString *email; [emailList addObject:@"Select an Email"]; for(int i=0; i&lt;substrings.count;i++){ email = [substrings objectAtIndex:i]; [emailList addObject:email]; // add emails in emailList } [substrings release]; } if (nil != s) { NSLog(@"%@",s); } [data release]; return [s autorelease]; } else { [data appendBytes: &amp;c length: 1]; } } return nil; } </code></pre> <p>output is:</p> <pre><code>* 1 FETCH (BODY[HEADER.FIELDS (FROM SUBJECT DATE)] {149} 2011-11-07 23:32:24.363 SwitchDeneme[327:bc03] Date: Mon, 07 Nov 2011 17:00:25 -0500 (EST) 2011-11-07 23:32:24.364 SwitchDeneme[327:bc03] From: "AOLWelcomeInfo" &lt;AOLWelcomeInfo@message.aol.com&gt; 2011-11-07 23:32:24.365 SwitchDeneme[327:bc03] Subject: Welcome to Your New Email Account! 2011-11-07 23:32:24.367 SwitchDeneme[327:bc03] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFString substringWithRange:]: Range or index out of bounds' terminate called throwing an exceptionsharedlibrary apply-load-rules all </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload