比较两个NSString类型的字符串时,应用程序崩溃

时间:2012-06-28 21:39:51

标签: iphone objective-c ios

我只是将“isEqualToString:”与我的iPhone App中的字符串进行比较。 var值是文本,“subInput”是文本字段之外的字符串。直到输入字段的第一个字符与文本的第一个字符相同时,一切都顺利。但是当它们不适合时,应用程序崩溃了。在开始之后键入错误的字符时,一切正常。

subInput = [[NSString alloc] initWithString:[theInput text]];
compare = [[NSString alloc] initWithString:[value substringToIndex:subInput.length]];

if([subInput isEqualToString:compare]){
//Here the app stops working

我也尝试将结果与“!= 0”或“!= nil”进行比较,但也无效。


其他代码

if([subInput isEqualToString:compare] != nil){
        NSLog(@"any");
        if([subInput isEqualToString:value]){
            NSLog(@"other");
            NSLog(@"well done");
            theInput.enabled = FALSE;
            lastValid = theInput.text;
            theMessage.backgroundColor = [UIColor orangeColor];
            theMessage.text = @"WELL DONE!!!!";
            theMessage.textColor = [UIColor blackColor];

            //save points for remaining seconds
            score += seconds*10;
            //invalidate counter when typed in all text correct
            [count invalidate];
            [self newTimer:3.0];
        }else{

            if(theInput.text.length >= range){
                NSLog(@"SCROLLEN");
                [theText setSelectedRange:NSMakeRange(range, addRange)];
                range += addRange;
            }
            //NSLog(@"String is ok");
            //self.view.backgroundColor = [UIColor blackColor];
            lastValid = theInput.text;
            theMessage.backgroundColor = [UIColor greenColor];
            theMessage.text = @"GO GO GO";
            theMessage.textColor = [UIColor whiteColor]; 
        }

    } else{
        //incrementing the fail var for every wrong letter
        fails++;

        theInput.text = [@"" stringByAppendingString:lastValid];
        theMessage.backgroundColor = [UIColor redColor];
        theMessage.text = @"WRONG CHARACTER!!!";
        theMessage.textColor = [UIColor whiteColor];
        if (grade >= 2) {
            seconds -= 2;
        }

        if(grade == 3){
            int actual = theInput.text.length;
            actual--;
            NSString *shorterString = [theInput.text substringToIndex:actual];
            lastValid = shorterString;
            theInput.text = shorterString;

        }
        //change bg-color to iritate the player
        self.view.backgroundColor = [UIColor colorWithRed:[self r:255]/255.0 green:[self r:255]/255.0 blue:[self r:255]/255.0 alpha:1];
    }

2 个答案:

答案 0 :(得分:2)

您还需要检查[输入文本]是否为零。

subInput = [[NSString alloc] initWithString:[theInput text]];

[NSString initWithString:(NSString *)aString]上的文档清楚地表明,如果尝试使用nil值进行初始化,将会出现异常。

答案 1 :(得分:0)

您需要检查并查看值的长度是否大于subInput的长度。如果不是,你就会离开那里。