Check NSString Failure Substring

I tried to check for substring in NSString in two ways: both of them crashed. This is an NSString object that I get from one of my NSManagedObject properties.

  • Using NSRange

    NSString *searchString = @"drive";

    NSRange range = [text rangeOfString:searchString options:(NSCaseInsensitiveSearch)];

    if (range.location! = NSNotFound) {NSLog (@ "Found"); }

  • Using NSScanner

    NSScanner *scanner = [NSScanner scannerWithString:text];

    NSLog (@ "% d", [scanner scanString: searchString intoString: nil]);

Both of them work when text = @ "drive", but cause EXC_BAD_ACCESS to crash when the text is "i drive" or "drive to". Nothing happens if the text is "idrive" or "driveto".

Even a stranger, sometimes examples throw NSInvalidArgumentExceptions, saying that I tried to pass an NSCFSet or DateComponents object to rangeOfString:, none of which I use in my application.

Any ideas?

+5
2

EXC_BAD_ACCESS "---weren't ", , , , .

, , . , , - "x ". , , EXC_BAD_ACCESS

+5

, .

NSString *string = @"hello one two three";
if ([string rangeOfString:@"one two"].location == NSNotFound) {
    NSLog(@"string does not contain substring");
} else {
    NSLog(@"string contains substring!");
}

, , . , , .

+5

All Articles