Objective-c子串范围异常

时间:2011-11-08 04:56:23

标签: iphone objective-c ios substring fetch

我正在创建一个imap客户端。我想解析传入数据的正文和标题,但它崩溃了。我无法理解为什么它崩溃并给出子串超出范围错误。我该如何解决?

我只想检查传入的字符串是否包含“FETCH”,所以我解析数据,因为字符串就像 * FETCH或* 1 FETCH我认为检查isEqualToString范围(4,6)就足够了但是没有用。

- (NSString*) readLine
{
    NSMutableData* data = [[NSMutableData alloc] init];
    unsigned char c;
    for (;;) {
        recv(socket_, &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:&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<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: &c length: 1];
        }
    }
    return nil;
}

输出是:

* 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" <AOLWelcomeInfo@message.aol.com>
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

2 个答案:

答案 0 :(得分:2)

问题是你的字符串可能短于7个字符,这意味着它的索引不是6。

尝试更像这样的事情:

NSRange range = [someString rangeOfString:@"FETCH "];
if( range.location != NSNotFound ) {
   //found it... so now do you processing...
}

答案 1 :(得分:0)

您分配并初始化NSData对象,然后使用该空数据对象初始化字符串,以便该字符串为空。