< Previous PageNext Page > Hide TOC

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.



< Previous PageNext Page > Hide TOC


© 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-10-15)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.