A formatter is an object that automatically converts a string representation of a value to an object representing that value, and vice versa. For example, an
NSNumberFormatter object can convert the string “1.25” to an
NSNumber object representing the value 1.25. An
NSDateFormatter; objects can convert an
NSDate object representing December 12, 2009 to “11/22/2009”. As you can see, the conversion works both ways, from string to value object and value object to string. The abstract base class for formatters is
NSFormatter. You may subclass
NSFormatter to create formatters for other types of data, even custom data types defined by your application’s data model.
Configuring and Applying a Formatter
When you create a date or number formatter object, you can configure it in many ways, but the primary attributes are formatter style and locale. You can give
NSNumberFormatter objects a decimal, currency, percent, scientific, or “spell-out” style (for example, “25” to “twenty-five”). You can give
NSDateFormatter objects both date and time styles in a range of explicitness, for example, from “11/22/2009” to “Sunday, November 22, 2009 AD”.
You may also apply an
NSLocale object to a formatter object so that it reflects a certain locale; for example, “1.02” in U.S. English would be “1,02” in French. To get the current locale (set by the user), call the
NSLocale class method
After you have configured a date or number formatter, you apply it to a string obtained from the user interface (typically a text field) to obtain the value object; or you apply it to an
NSNumber object and write the resulting string to an object in the user interface. The methods you call for these purposes are
In OS X, You Can Attach a Formatter to a Cell
On OS X, you can associate a number or date formatter object with a cell object, either programmatically or in Interface Builder. The conversion between string and number or date object occurs automatically—you do not have to call any method to perform the conversions. The cell object can be associated with objects other than text fields. For example, you can assign formatter objects to the cells in a table view or outline view.