iOS Reference Library Apple Developer
Search

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

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:

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 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

Did this document help you? Yes It's good, but... Not helpful...