Quick Tip: Keep your imports nice & tidy
After watching WWDC 2012 session 402 about working efficiently with XCode, I came across a nifty little tweak that may benefit anyone who strives to keep their code clean and tidy. You know how complex classes may sometimes end up with multiple “import” lines and that you can even sometimes loose track of what classes have already been imported? I’m going to show you how to add a new context menu option via Mac OS X’s Automator that does just what you need:
Step 1: Open Automator – It should be fairly easy to find via spotlight or just go the Applications folder and look for a robot that looks like a pissed-off version of Eve from WALL-E
Step 2: Once you open Automator, you’ll be asked about what type of document you wish to create. Select “Service”.
Step 3: In the workflow inspector, mark the “Service recieves selected” with “text”. Next, you can decide that you want this new service to be available only in XCode or in any other app you’re running, I just left it with the default “any application”. Be sure to tick the “Output replaces selected text” so that the operation will replace the imports you’ll select in XCode.
Step 4: In the “Actions” panel on the left, select “Run Shell Script” as shown here:
Step 5: Fill in “sort | uniq” to the script body, like so:
Step 6: hit cmd+s to save your automated service and give it a nice pet name, such as “Igor” or the preferable “Sort & Uniq”. This is what you’ll see in the context menu when right-clicking on selected text.
Step 7: Use it: Open XCode, go to any of your complex classes that have way too much imports, select those imports and right click them. You’ll see the new “Sort & Uniq” option appear under “services” – once you select that, you’ll see that your imports are instantly sorted and any duplicates will be thrown out.
If you have any other handy ideas about how to use automator to improve XCode use, please share with us through the comments section.
And a happy New Year!