More specific NSNumberFormatter failure behaviour
I have an NSTextField
into which I need the user to enter a number between a max and min, and it would be nice if I could detect when the NSNumberFormatter
fails that particular test so I can either display a nicer message ("The number is too large" is not very helpful, it needs to display the valid range) or simply set the field automatically to the nearest valid value.
I've looked at the NSTextField
delegate's ‑control:didFailToFormatString:errorDescription:
method which doesn't seem to allow you to modify the error, and I've looked at overriding the NSNumberFormatter
's ‑getObjectValue:forString:range:erro开发者_JAVA百科r:
method which does give me an NSError
that I can modify, but there doesn't seem to be any way to determine which specific error was returned.
Since I am just entering a simple integer, I don't need most of the functionality in NSNumberFormatter
, would I be better off just writing my own formatter from scratch?
There is a way to determine which error is returned in an NSError. The NSError error codes documentation defines errors for both max and min validation fails. Just send -code to your NSError object.
I would recommend that instead of enforcing those limits in the NSNumberFormatter
, that you enforce them in the logic that occurs on textDidChange:
. From your description you sound like you might be using interface builder to connect your number formatter. Instead I would make your controller a NSTextFieldDelegate
for the particular textfields. Then you get to directly handle the interaction with the number formatter and you can set the text for a particular error label appropriately. Additionally this allows you to give more complex context dependent fallback values. Aka: in some cases you might always want the number to fall back to a mid range, or to the lower end, or to an older value, or to whichever edge the user ran over. This would also allow you to enforce blackout ranges, or coerce exceptionally long decimals into neat specific precision.
精彩评论