PDA

View Full Version : NSScanner not continuing scan




Spike099
Apr 7, 2008, 01:25 AM
Hello everyone.

I am having a issue with the NSScanner. If I use a space as the scanners delimiter to iterate through the scanner's string, it works perfectly. However when I change it to a period, the scan stops at the first period and will not find the rest(and there are more).

I was playing around with code collector, i put a sample piece of code there for fun. The snippet is how I am currently using the scanner for my above issue.

http://www.codecollector.net/images/snippetbutton.png (http://www.codecollector.net/view/746/simple_use_of_nsscanner)

Thanks guys!



kainjow
Apr 7, 2008, 07:19 AM
Can you post the code that is using the period?

Sayer
Apr 7, 2008, 10:51 AM
The code you posted does exactly what its written to do.

NSScanner does iterate, but it stops when the first match is found. To find the next match you have to do a little more work.


Example:

// find start tag
if (![theScanner scanUpToString:gAlertBeginStr intoString:nil]) {

...

}

// skip over the start tag we found
[theScanner scanString:gAlertBeginStr intoString:nil];

// then scan up to the end tag in the result
[theScanner scanUpToString:gAlertEndStr intoString:&currentAlert];

// see if the end tag actually exists, if so return the result, if not return nil
if (![theScanner scanString:gAlertEndStr intoString:nil]) {

...

}

If you do a scanUpToString then the NSScanner stops at the first match it finds, which is what your code does and is technically correct as written. So to then skip the first match you do scanString: with a nil intoString.

So you need to write a bit more code in the while loop to add the skip step.

Spike099
Apr 7, 2008, 11:07 AM
This code is called whenever my class receives a textViewDidChangeSelection notification. Depending on what the user last typed, would determine the delimiter. So I call it like this [self scan:@"."]... When I call this method using a period as the delimiter, I get a NSLog of the first sentance, but it never logs the other ones. They should all get logged no matter what.

- (void)scan:(NSString*)delimiter {
NSScanner *scanner = [NSScanner scannerWithString:[txtContents string]]; // txtContents is a NSTextView
NSString *result;

NSSpeechSynthesizer* synth = [[NSSpeechSynthesizer alloc] init];
while([scanner scanUpToString:delimiter intoString:&result]) {
NSLog(@"\n****\nSearching\n****\n\n scan loc %d", [scanner scanLocation]);
if ([scanner scanLocation] == lastEditedRange.location) {
NSLog(@"\n****\nFound\n****\n\n%@", result);
[synth startSpeakingString:result];
}
}
[synth release];
}

Spike099
Apr 7, 2008, 11:10 AM
Sayer, thanks a ton, works like a charm now. Thanks for the help guys!