Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Spike099

macrumors regular
Original poster
Feb 18, 2007
143
0
Canada
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.



Thanks guys!
 

Sayer

macrumors 6502a
Jan 4, 2002
981
0
Austin, TX
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:

Code:
// 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

macrumors regular
Original poster
Feb 18, 2007
143
0
Canada
The code

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:mad:"."]... 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.

Code:
- (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];
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.