Home > Articles > Programming

  • Print
  • + Share This
From the author of Alternatives

Alternatives

Attributed strings would have been an obvious way of implementing things like spell-checking services, regular expressions, and so on. Instead, Apple decided to add a new class: NSTextCheckingResult. This class serves the same general purpose as an attributed string: It defines an attribute on a range or set of ranges in a string. Unlike an attributed string, however, it's designed to be stored externally to the string, and therefore doesn't automatically update when text is inserted into a string. This characteristic makes it more useful for transient attributes.

You can add new NSTextCheckingResult subclasses to return specific data for something that tags strings. For example, if you're writing a machine-translation application or a grammar checker, one of the first things you need to do is tag parts of speech. You could add these attributes to an attributed string, or you could return an array of NSTextCheckingResult objects. The latter might be more convenient for pattern-matching later on, since you'd match on the types of the checking results and only go back to the original string after a successful match.

Whenever you do any text processing, it's worth considering NSAttributedString. It may not be the best tool for the job, but often it's good enough for the prototype, and in many cases good enough for the final version, too.

  • + Share This
  • 🔖 Save To Your Account