Formatters and User Interface Elements

This article describes how to associate a formatter with a cell in Cocoa. This article does not apply to iOS.

Associating a Formatter With a Cell

In Cocoa, user interface cells that display text but have an arbitrary object as their content can use formatters for both input and output. When a cell is displayed, the cell converts an arbitrary object to a textual representation. How a cell displays the object depends on whether or not the cell has an associated formatter. If a cell has no formatter, the cell displays its content by using the localized representation of the object. If the cell has a formatter, the cell obtains a formatted string from the formatter. When the user enters text into a cell, the cell converts the text to the underlying object using its formatter.

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.

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's 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:)

When a cell with a formatter object is copied, the new cell makes a strong reference to the formatter object rather than copying it.

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.

Delegation Methods for Error Handling

NSControl has delegate 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:.