Making NSNumberFormatter empty-tolerant
Making NSNumberFormatter empty-tolerant
- Subject: Making NSNumberFormatter empty-tolerant
- From: Markus Spoettl <email@hidden>
- Date: Thu, 27 Aug 2009 20:45:35 +0200
Hello,
before I get to the question this is my setup:
1) NSTextField ("field")
2) bound to an NSNumber property ("number") of an object.
3) "field" has an NSNumberFormatter attached with all default
values (as set up by IB), except maximum fraction digits is set to
1.
4) "number" can be nil - in fact it is when we start our app.
Starting this little app, one can tab into and out-of an the empty
field, nothing happens. This as expected and what I want.
When you enter a value and tab out, "number" gets set to the new
value. If you now attempt to remove the value by emptying the field
you will get formatting error message. This is kind of unexpected as
the empty field was fine with the formatter moments ago.
In other words, once the value is set to something non-nil it never
can get nil again. I would like to be able to nil out a number by
clear a field.
My solution for this is a sub-class of NSNumberFormatter which
implements -getObjectValue:forString:range:error: as follows:
- (BOOL)getObjectValue:(out id *)anObject
forString:(NSString *)aString
range:(inout NSRange *)rangep
error:(out NSError **)error
{
BOOL result = [super getObjectValue:anObject forString:aString
range:rangep error:error];
if (!result && ((aString == nil) || ([aString
isEqualToString:@""]))) {
*anObject = nil;
result = YES;
}
return result;
}
The docs tell me that I have to feed a valid NSNumber into anObject
when returning YES - nil is valid therefore this should be OK.
The question is: Is this safe? Do I overlook an aspect that I'd better
not? Or even better, is there a simpler solution?
Regards
Markus
--
__________________________________________
Markus Spoettl
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden