More specific NSNumberFormatter crash behavior

I have an NSTextField in which I need the user to enter a number between the maximum and minimum, and it would be nice if I could detect when the NSNumberFormatter fails in this particular test so that I can either show a more pleasant message ("Too a large number "is not very useful, it needs to display a valid range) or just set the field automatically to the nearest valid value.

I looked at the NSTextField delegate ‑control:didFailToFormatString:errorDescription: , which doesn't seem to allow you to change the error, and I looked at overriding the NSNumberFormatter ‑getObjectValue:forString:range:error: method, which gives me an NSError that I can change, but There seems to be no way to determine which specific error was returned.

Since I just go into a prime integer, I don't need much of the functionality in NSNumberFormatter , is it better for me to write my own formatter from scratch?

+6
validation objective-c cocoa macos nsnumberformatter
source share
2 answers

There is a way to determine which error is returned in an NSError. The NSError error code documentation defines errors for checking max and min. Just send - code to your NSError object.

+1
source share

I would recommend, instead of applying these restrictions to NSNumberFormatter , that you apply them in the logic that occurs on textDidChange: From your description, it seems to you that you can use the interface builder to connect your number formatting. Instead, I will make your NSTextFieldDelegate controller for specific text fields. Then you can directly handle the interaction with the number formatter, and you can set the text for a specific error label accordingly. In addition, it allows you to give more complex context-dependent values. Aka: in some cases, you can always want the number to return to the middle range, or to the lower end, or to an older value, or to the edge that the user used. It will also allow you to enforce obscuration ranges or force extremely long decimal places to neat concrete accuracy.

+1
source share

All Articles