Filtering NSTextField – Take 2

Thanks to Jim Correia of Bare Bones Software, I have a slightly different method for filtering NSTextFields based on an NSFormatter. While my older method worked, this is a bit cleaner.

Like my old filter, this also has three methods:

- (void) setAcceptableCharacterSet:(NSCharacterSet *) inCharacterSet;
- (void) setMaximumLength:(int) inLength;
- (void) setMaximumValue:(int) inValue;

However, they’re called differently. You’d do something like this:

NSMutableCharacterSet *characterSet = [[NSMutableCharacterSet alloc] init];
[characterSet addCharactersInString:@"0123456789"];
[secondaryTextField setFormatter:[[[PartialFormatter alloc] init] autorelease]];
[[secondaryTextField formatter] setMaximumValue:65535];
[[secondaryTextField formatter] setAcceptableCharacterSet:characterSet];
[characterSet release];

Note that the formatter is based on NSFormatter and not NSNumberFormatter. I actually am using this for a number field as I want the number field to give me back a string instead of a number, so that’s why I put in the setMaximumValue and didn’t base it on NSNumberFormatter.

As always, feedback is welcome.

The attached code can be freely used in commercial and non-commercial projects. While I’d like some credit in the about box, it isn’t necessary. This code has no warranty and you assume all risk for using it.

Download source

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the answer to the math equation shown in the picture. Click on the picture to hear an audio file of the equation.
Click to hear an audio file of the anti-spam equation