8

There are a lot of specialized subclasses of NSFormatter:

CNContactFormatter
CNPostalAddressFormatter
DRMSFFormatter
MKDistanceFormatter
NSByteCountFormatter
NSDateComponentsFormatter
NSDateFormatter
NSDateIntervalFormatter
NSEnergyFormatter
NSLengthFormatter
NSMassFormatter
NSNumberFormatter
NSPersonNameComponentsFormatter

Most of us have used NSNumberFormatter and NSDateFormatter. Those have a locale property that lets you specify what locale to use when converting from strings to/from the "native" format the formatter supports. Some others like NSDateComponentsFormatter inherit their locale from one of their properties (NSDateComponentsFormatter uses the locale of the specified calendar, if any.)

Most of the others don't seem to have any way to specify a locale. The only way I can think of to get them to generate output in a specific language/locale is to set the system locale, get the output/convert a string to numeric format, and then set it back.

Is there a way to set the locale for formatters like NSByteCountFormatter that don't seem to offer a locale setting of any kind?

Edit:

Since I wrote this question the names of a lot of the formatters above have changed. Most (all?) have lost their "NS" prefix.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Only 4 of those classes lack a `locale` (directly or indirectly). They are `NSByteCountFormatter`, `DRMSFFormatter`, `CNPostalAddressFormatter`, and `CNContactFormatter` – rmaddy Apr 10 '16 at 16:40
  • It seems very unlikely. If you walk through the implementation, `NSByteCountFormatter` uses an internal function `_NSLocalizedFileSizeDescription`, which relies heavily on `-[NSBundle localizedStringForKey:value:table:]` (calling into Foundation's bundle). There's nowhere to pass a locale into that. I would open a radar requesting a `numberFormatter` property for `NSByteCountFormatter` to match `NSEnergyFormatter`. – Rob Napier Apr 10 '16 at 16:50
  • Note that the use of `NSNumberFormatter` is very inconsistent. For instance, `NSEnergyFormatter.unitStringFromJoules(_:usedUnit)` does not correctly localize based on the locale of the `NSNumberFormatter`. But `stringFromJoules` does. – Rob Napier Apr 10 '16 at 16:52
  • @RobNapier why don't you post your "well, for some formatters you can't" comment as an answer so I can accept it? This question has remained unanswered for a good long time. – Duncan C Jan 05 '22 at 14:13

1 Answers1

1

It seems very unlikely. If you walk through the implementation (in Hopper), NSByteCountFormatter uses an internal function _NSLocalizedFileSizeDescription, which relies heavily on -[NSBundle localizedStringForKey:value:table:] (calling into Foundation's bundle). There's nowhere to pass a locale into that. I would open a radar requesting a numberFormatter property for NSByteCountFormatter to match NSEnergyFormatter.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610