views:

124

answers:

1
+1  Q: 

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?

+3  A: 

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.

Chuck
I knew I was missing something simple! I used if([string rangeOfString:@"'"].location != NSNotFound) { return 2; }To replace the above code.
Chris