Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
From the author of

Services are designed to be invoked explicitly by the user, but that doesn't mean that you can't use them yourself. One use for them might be integration between applications in a suite. Each application might expose a few services that any other program could use, but provide default user interface elements for using them from the other parts of the suite. You might also hide or show them depending on whether the other application was installed.

Using a service is quite simple. You first need to prepare a pasteboard that contains the data that you want to send, then you need to find the service, and finally you need to retrieve the pasteboard that contains the result.

Using services in the standard Cocoa views works automatically. For custom views, you need to override a few methods validating the potential types. This allows the services menu to hide all services that are never applicable in an application and to disable the ones that don't apply to the current selection.

More interestingly, you can perform named services with a single function, NSPerformService(). This takes the name of a service and a pasteboard as arguments. If you store the name of a file on a pasteboard, for example, you can pop up an inspector for it like this:

	NSPerformService(@"Finder/Show Info", pboard);

This invokes the Finder's Show Info service on the pasteboard, causing the inspector for that file to be opened. This particular service doesn't return anything, so the pasteboard is useless afterwards. Other services will return data on the pasteboard.

One important thing to note is that this function is synchronous, and doesn't require a run loop. That means that you can use it from any program, including command-line applications. One of the strengths of OS X is how well it integrates the GUI and the command line, with tools like open, which opens a file in the default GUI app, and pbcopy and pbpaste for moving data between the command line and pasteboards. If you are writing a command-line tool for OS X then you might want to consider integrating support for services.

  • + Share This
  • 🔖 Save To Your Account