Vik
Vik

Reputation: 341

NSNumberFormatter failing with nil value

I must be missing something very obvious, but I have looked all over and cannot find a solution.

In Interface Builder I have hooked up a NSNumberFormatter to a NSTextField, I have bound the value to a float value. It all works as expected, the number gets validated and updated. Unless I enter an empty string, in which case I get an exception:

Exception detected while handling key input.
[<ResolutionSetting 0x11d029430> setNilValueForKey]: could not set nil as the value for the key scale.

Is there any way to have the NSTextField return an empty string (@"") instead of nil if the text field is empty? Alternatively, is there a way to have the NSNumberFormatter handle nil values?

Upvotes: 2

Views: 991

Answers (2)

John
John

Reputation: 1447

Set the nilSymbol of your NSNumberFormatter to a non-empty string.

The NSTextField then no longer throws an exception but complains to the user that "" is an invalid value. I'm not sure why this works but it's the easiest solution I've found.

yourNumberFormatter.nilSymbol = "?"

Upvotes: 1

Eugene Tulushev
Eugene Tulushev

Reputation: 146

The default behavior of setNilValueForKey: method is to raise an exception. You need to implement this method in your code to override the default behavior. For example to assign a 0.0 value when nothing is entered. Example:

- (void)setNilValueForKey:(NSString *)key{
//here you can either assign @"" or 0.0
}

You can also specify minimum and maximum values in number formatter attributes inspector.

This topic is covered in "Key-Value Coding Programming Guide" in apple documentation, and also in Chapter 7 of "Cocoa programming for Mac OS X".

Upvotes: 1

Related Questions