Le 27 août 09 à 20:45, Markus Spoettl a écrit :

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?

I had the same problem. For the 10.4 behaviour of NSNumberFormatter, you don't have to subclass it.

Just set the nil symbol with:

[myNumberFormatter setNilSymbol:@""];

Alternatively, you can set it in IB:

In the number formatter attribute palette, go down until you see Nil Symbol, enter a character and then delete it.


Note: if only the NSDateFormatter has the same attribute.

Frédéric_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to