Question

NSString*test=[NSString stringWithString:inputString]; 
NSScanner*scan;
BOOL pass= [scan scanUpToCharactersFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet] intoString:&test];

The last line crashes the app with bad access. Does it have something to do with the address symbol, &? I'm not clear on why it needs this type of syntax anyway.

I am trying to simply check with my BOOL if the inputString contains any non-alphanumeric characters. If it does, pass becomes YES.

UPDATE: I see I do not understand scanner entirely. I understand this output:

NSString*test=@"Hello"; // this should cause my BOOL to be NO since no characters are scanned
NSScanner*scanix=[NSScanner scannerWithString:test];
BOOL pass= [scanix scanUpToCharactersFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet] intoString:nil];
NSLog(@"pass is %i for %@",pass, test);

Result in log: pass is 1 for Hello

What I want is to know if in fact the test string contains non-alphanumeric characters. How would I factor such a test into this?

Was it helpful?

Solution

What I want is to know if in fact the test string contains non-alphanumeric characters. How would I factor such a test into this?

You don't need to use NSScanner if this is your only goal. You can simply use NSString's -rangeOfCharacterFromSet: method:

NSCharacterSet *nonAlphanumeric = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
pass = ([test rangeOfCharacterFromSet:nonAlphanumeric].location != NSNotFound);

OTHER TIPS

You are supposed to initialise your scanner with the string to parse,

    NSScanner *scan =[NSScanner scannerWithString:mystring];

You are mixing up the destination string and the source string. Your source is test. Also, your scanner is not initialized.

NSScanner *scan = [NSScanner scannerWithString:test];
BOOL didScanCharacters = [scan scanUpToCharactersFromSet:
   [[NSCharacterSet alphanumericCharacterSet] invertedSet] 
   intoString:nil];

The EXC_BAD_ACCESS error occurs because you are sending a message to a nonexistent object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top