Migrating to Obj-C Literals

By: Jeremy W. Sherman. Published: . Categories: tools obj-c scripts.

Obj-C literals make your code cleaner and more compact, but hand-updating a large codebase to take advantage of Obj-C literals would be a bore, and all too easy to mess up during a distracted moment.

This is what automated refactoring tools were designed for. And Apple has provided us with an oft-overlooked arrow in our devtools quiver that’s just what we need here: tops.

Check out man tops. The tool has a decent understanding of Obj-C syntax and accepts scripts that let you rewrite code to use new method calls, new functions, and what-have-you. The examples make it look like this tool was invented to ease the transition from NeXT-style Obj-C to Cocoa, like this gem:

replace "NXGetNamedObject(<b args>)" with same
    error "ApplicationConversion: NXGetNamedObject() is obsolete.
           Replace with nib file outlets."

That should take some of you way back.

Anyway, with this tool, modernizing your code can be as simple as:

tops -semiverbose -scriptfile literals.tops **/*.(h|m|hpp|mm)

Want to check that it will do the right thing? Throw -dont into the args.

Want to watch over its shoulders as it rewrites your code? Replace -semiverbose with straight-up -verbose.

Now, for that magical script file:

And here’s an Obj-C file to test it against: