Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many obscure subclasses of `NSFormatter` are there? Know of any others?

If you're used Cocoa for a while you're probably familiar with NSDateFormatter and NSNumberFormatter. They're handy for creating formatted display strings from dates and numbers, or for converting date or number strings into numeric values, while supporting different languages and locales.

A few weeks ago I stumbled on NSDateComponentsFormatter, which lets you create formatted time intervals like "4 hours, 37 minutes and 17 seconds." Pretty cool.

There's also the related NSDateIntervalFormatter, which creates strings by comparing 2 dates.

Then there are some REALLY obscure NSFormatter subclasses:

NSMassFormatter
NSByteCountFormatter
NSLengthFormatter
NSEnergyFormatter
NSPersonNameComponentsFormatter

EDIT:

From the comments, I've aded NSPersonNameComponentsFormatter.

Searching on "NS*Formatter" in the Xcode help system reveals most of these, but not all. (It looks like the help text has to be indexed correctly in order for searching to work, which is annoying.)

That brings the total I have been able to find to

NSDateIntervalFormatter    -Difference between 2 dates
NSDateComponentsFormatter  -NSDateComponents to/from string
NSDateFormatter            -Formats NSDates as strings
NSNumberFormatter          -Formats numbers as strings
NSMassFormatter            -Formats mass quantity as strings 
NSByteCountFormatter       -Formats byte counts in K, MB, GB, etc.
NSLengthFormatter          -Formats length values
NSEnergyFormatter          -Displays energy qualities in Joules or Calories
NSPersonNameComponentsFormatter - displays localized formatted names

Annoyingly, it looks like many of these formatters don't have a locale property, so it's not very easy to use them to create formatted strings in languages/locales other than the system's default locale. If I'm missing something, please tell me.

Does anybody else know of other formatters I'm missing? These are pretty obscure, but could save you a lot of time if you were to need them.

EDIT #2:

Question part 2: Is there a way to get output from the formatters that lack a locale property in locale's other than the system default locale? It seems silly that they don't ALL have and honor a locale property. It's pretty common to need to generate output for languages/locales other than the current locale.

like image 634
Duncan C Avatar asked Mar 13 '23 15:03

Duncan C


1 Answers

There's no need to search. The NSFormatter documentation lists all of its subclasses. Look at the top of the page, in the "inherits from" block.

enter image description here

Note that this information is not available in the Xcode 7.3 doc reader. It's only available in the online docs (or by using the excellent Dash reader).

like image 177
Rob Napier Avatar answered Apr 09 '23 00:04

Rob Napier