This article describes how to associate a formatter with a cell in Cocoa. This article does not apply to iOS.
The easiest way to use a formatter is in Interface Builder to drag it from the palette onto a control such as a text field or a column in a table view. You can then configure the behavior you want using the inspector—typically you should use v10.4 behavior.
To create a formatter object programmatically and attach it to a cell, you allocate an instance of the formatter and set its format or style as you wish. You then use the NSCell
setFormatter:
method to associate the formatter instance with a cell. The following code example creates and configures an instance of NSNumberFormatter
, and applies it to the cell of an NSTextField
object using the setFormatter:
method.
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; |
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; |
[[textField cell] setFormatter:numberFormatter]; |
Similarly, you can create and configure an instance of NSDateFormatter
object programmatically. The following example creates a date formatter then associates it with the cells of a form (contactsForm
).
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; |
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; |
[dateFormatter setTimeStyle:NSDateFormatterNoStyle]; |
[[contactsForm cells] makeObjectsPerformSelector:@selector(setFormatter:) |
withObject:dateFormatter] |
Instances of formatter objects are immutable. In addition, when a cell with a formatter object is copied, the new cell retains the formatter object rather than copying it.
The type of object that you retrieve from a cell using the method objectValue
depends upon the behavior of the formatter:
For a number formatter, using Mac OS X version 10.0 behavior it would be a NSDecimalNumber
object; using 10.4 behavior it would be by default a NSNumber
object.
For a date formatter, using Mac OS X version 10.0 behavior it would be a NSCalendarDate
object, using v10.4 behavior it would be by default a NSDate
object.
When the cell needs to display or edit its value, it passes its object to the formatter which returns the formatted string. When the user enters a string, or when a string is programmatically written in a cell (using setStringValue
), the cell obtains the corresponding object from the formatter.
NSControl
has delegation methods for handling errors returned in implementations of NSFormatter
’s getObjectValue:forString:errorDescription:
, isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange:errorDescription:
, and isPartialStringValid:newEditingString:errorDescription:
methods. These delegation methods are, respectively, control:didFailToFormatString:errorDescription:
and control:didFailToValidatePartialString:errorDescription:
.
Last updated: 2009-08-06