Creating a Custom Formatter

You can create custom subclasses of NSFormatter to format representations of data other than dates and numbers.

To subclass NSFormatter, you must, at the least, override these 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.

You may also override attributedStringForObjectValue:withDefaultAttributes: to 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:.

In OS X, you can edit the textual contents of a cell at each key press 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 social security numbers; the person entering data enters the number only once, since the formatter automatically inserts the separator characters.