iOS Reference Library Apple Developer
Search

Creating a Custom Formatter

You can create various custom subclasses of NSFormatter. For example, you might want a custom formatter of telephone numbers, or a custom formatter of part numbers.

To subclass NSFormatter, you must, at the least, override the three primitive methods:

In the first method you convert the cell’s object to a string representation; in the second method you convert the string to the object associated with the cell.

In the third method, attributedStringForObjectValue:withDefaultAttributes:, you convert the object to a string that has attributes associated with it. For example, if you want negative financial amounts to appear in red, you have this method return a string with an attribute of red text. In attributedStringForObjectValue:withDefaultAttributes: get the non-attributed string by invoking stringForObjectValue: and then apply the proper attributes to that string.

If the string for editing must differ from the string for display—for example, the display version of a currency field shows a dollar sign but the editing version doesn’t—implement editingStringForObjectValue: in addition to stringForObjectValue:.

You can edit the textual contents of a cell at each keypress and prevent the user from entering invalid characters using isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange:errorDescription: and isPartialStringValid:newEditingString:errorDescription:. You can apply this dynamic editing to things like telephone numbers or social security numbers; the person entering data enters the number only once, since the formatter automatically inserts the separator characters.




Last updated: 2009-08-06

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