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

Screen Shot 2012-12-29 at 2.12.13 PM

Step 2: Once you open Automator, you’ll be asked about what type of document you wish to create. Select “Service”.

Screen Shot 2012-12-29 at 12.40.55 PM

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.

Screen Shot 2012-12-29 at 12.45.05 PM

Step 4: In the “Actions” panel on the left, select “Run Shell Script” as shown here:

Screen Shot 2012-12-29 at 12.45.59 PM

Step 5: Fill in “sort | uniq” to the script body, like so:

Screen Shot 2012-12-29 at 12.47.02 PM

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.

Screen Shot 2012-12-29 at 12.52.13 PM

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!

Posted on December 29, 2012, in Quick tips and tagged , , , , . Bookmark the permalink. 2 Comments.

  1. Nifty trick with automator, thanks. I’ll try to set it up for some daily tasks.

Leave a reply to SutoCom Cancel reply