Chris
Chris

Reputation: 419

Validate NSString

I am validating an NSString to ensure that the string does not contain apostrophes.

The code I'm using to do this is

NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:@"'"];
NSScanner * scanner = [NSScanner scannerWithString:string];
NSString  * scannerResult;
[scanner setCharactersToBeSkipped:nil];
[scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult];
if(![string isEqualToString:scannerResult])
{
    return 2;
}

Returning 2 represents an error. This code works, except for the case where the string is an apostrophe.

To get around this issue, I added the following code above the preceding block.

if([string isEqualToString:@"'"]);
{
    return 2;
}

This code is evaluating to true, regardless of the input. I need to either prevent the first block from crashing with the input of ', or get the second block to work.

What am I missing?

Upvotes: 1

Views: 641

Answers (1)

Chuck
Chuck

Reputation: 237080

There's no logical reason why the isEqualToString: test should always succeed. If that's your actual, copy-pasted code, you must have an error somewhere else in the function.

At any rate, it would be much simpler to test if the location of [string rangeOfString:@"'"] is NSNotFound.

Upvotes: 3

Related Questions