Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4370

Supercharging Your Xcode Efficiency

$
0
0
Learn some cool Xcode Tricks!

Learn some cool Xcode Tricks!

You’ve all seen the all-star Hollywood programmer hacking through the mainframe, fingers racing on the keyboard while terminals fly across the screen. If you’ve ever wanted to be like that, you’re in the right place!

This tutorial will teach you how to be more like that programmer, in Xcode. Call it what you like — magic, mad skillz, pure luck or hacks, there is no doubt you’ll feel much cooler (and have improved Xcode efficiency) after following along this tutorial, and maybe even save the world from destruction with your newly found prowess.

Getting Started

Since coolness is the goal, here is what contributes towards coolness points in this tutorial:

  • Performing a task quickly.
  • Being precise and accurate.
  • Having clean and beautiful code.

To gain extra ninja points, you can try to accomplish each task without touching the mouse or track-pad. Yes, that’s the equivalent of going pewpew in Xcode.

Your studies will commence with learning a few useful Xcode features. Then, you’ll continue your training by fixing some bugs in CardTilt, which you might be familiar with from this tutorial. Finally, you’ll clean up the code a bit and make the interface pixel accurate.

Keep in mind that this tutorial is not about the final app; this lesson is about learning how to take advantage of Xcode to develop apps with more speed and grace than ever before.

This tutorial assumes a basic understanding of Xcode and focuses on techniques that improve your efficiency as a programmer. Everyone’s coding habits are different, so this tutorial is not meant to force a certain style on you.

Throughout, you’ll see alternatives to certain commands. When following along, just focus on refining and building on your current development style, and try not to let the subtle differences throw you.

Note: If you’re not confident working with Xcode yet, you can check out these tutorials here and here.

Download the CardTilt-starter and get ready to code!

Everyday Xcode Tasks

There are a few tasks in Xcode that you perform regularly in most projects. This section will take a close look at some of these tasks and talk about some tricks to tackle them with pizazz. As you progress, you’ll build upon these tricks and discover new ways to use them. These tricks will become the ninja stars and smoke bombs that are a must on your coding tool belt.

Open CardTilt in Xcode, but don’t dive into the code just yet. First, take a moment to match up what you see to the diagram of the Xcode Workspace Window below.

These labels are how this tutorial will refer to the individual parts of the workspace. If your setup doesn’t look exactly like this – don’t worry! In the Hotkeys section below, you’ll learn how to easily show and dismiss inconsistencies.

XCodeLayout
Here is a quick rundown of the individual views that make up the workspace interface:

  • The Toolbar: Where you choose your scheme and destination, run your app, and switch between common interface layouts.
  • The Navigation Area: Where you navigate through your project, symbols, errors, etc.
  • The Editing Area: Where all the magic happens. Includes the Jump bar at the top of this view.
  • The Utility Area: Includes the Inspectors and the Libraries.
  • The Debugging Area: Includes the Console and the Variable Inspector.

All of these views are essential to Xcode, and you’ll probably interact with every one of them when you’re working on a project. Usually you won’t need to look at them all at once though, and this next section will teach you how to configure your workspace quickly by using hotkeys.

The Hotkeys

On this journey of Xcode coolness, you’ll first learn how to master it with hotkeys. The most useful hotkeys are surprisingly easy to remember, thanks to a few patterns.

Prepare to be in awe of the intuitive nature of the following hotkeys.

The first pattern to know is the relation of the common modifier keys to various parts of Xcode.

Here’s a quick breakdown of the most common:

  • Command (⌘): Used for Navigation, and thus controls the Navigation area.
  • Alt (⎇): Controls things on the right side such as the Assistant Editor and utility editor.
  • Control: Interacts with the Jump Bar at the top of the editing area.

The second pattern to recognize is the relation of number keys to tabs. Combinations of number keys and the modifiers keys above will let you switch through tabs quickly.

Generally, the numbers correspond to the indexes (starting from one) of the tabs, and zero always hides or shows the area. Can it get any more intuitive?

The most common combinations are:

  • Command 1~8 to jump through the Navigators, Command 0 to close the navigation area.
  • Command Alt 1~6 to jump through the Inspectors, Command Alt 0 to close the utility area.
  • Control Command Alt 1~4 to jump through the Libraries.
  • Control 1~6 to bring down tabs in the Jump Bar.
  • hotkeys

    The last, and most simple pattern is the Enter key. When used with Command, they allow you to switch between editors:

    • Command + Enter: Shows the standard, single-window editor.
    • Command Alt Enter: You can probably guess what this does. Indeed, It opens the assistant editor.
    • Command Alt Shift Enter: Opens the revision control editor.

    Last, but not least, open and close the debugging area with Command + Shift + Y. To remember this just ask, “Y is my code not working?”

    You can find most of these hotkeys under the Navigate menu in Xcode, in case you forget.

    To finish off this section, rejoice in knowing that you can make Xcode dance for you by using only your keyboard!

    SC0-XCodeDance

    Stats:

    Coolness points gained:100

    Total Coolness points:100

    Ninja points gained:100

    Total Ninja points:100

    Xcode Behaviors

    Controlling the interface of Xcode using hotkeys is cool, but do you know what’s even more ninja? Having Xcode transform to the interface you want automatically. Now that’s the epitome of cool.

    Fortunately, Xcode provides Behaviors that let you do this very easily. They are simply a defined set of actions that are triggered by a specific event, such as starting a build. Actions range all the way from changing the interface to running a custom script.

    To see an example you’re familiar with, make a quick modification to CTAppDelegate.m so that running will generate console output. Replace didFinishLaunchingWithOptions with the following:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
        // Override point for customization after application launch.
        NSLog(@"Show me some output!");
        return YES;
    }

    Now build while carefully watching the Debugging Area. You’ll notice a familiar sight – the debugging area appears as soon as the app starts running:

    debug popup

    To see what defines this event, open the behavior preferences window by going to Xcode\Behaviors\Edit Behaviors. On the left, you’ll see a list of all the events; on the right, a list of the actions the events can trigger. Click on the Generates output event under Running and you’ll see it is set to show the debugger:
    output event

    Some Behavior Recommendations

    There are two different sets of actions I recommend for the Generates output event, depending on your development environment. If you have a dual-screen environment, try the first one. If you work on a single screen, try jumping ahead to the second method below.

    If you work on two or more screens, wouldn’t it be handy to have the debug console in its own window on your second screen? Well, you can set up the actions so it looks like this:
    two_monitor_debug

    Now build and run, and you’ll see a separate window appear. Position it on your secondary display, and just like that, you have yourself an efficient debugging setup!
    dual_display_console

    If you have a single screen environment, maximize the effective area for the console by hiding the utilities pane and setting the console to take up the entire debug area. To do this, set up the actions like so:
    single_monitor_debug

    Now run the app, and watch as Xcode automatically follows your commands!
    single_monitor_debug

    You’ll also want to change the behavior to account for when the project pauses. Go to Pauses event under Running, and change the settings like this:

    PausesBehavior

    Now whenever you hit a breakpoint, you’ll get a new tab named Fix that will display the variables and console views, and automatically navigate to the first issue. You should really think about demonstrating this next time you host a party, because it’s that cool.

    Well, maybe not…unless your guests are burgeoning coders.

    The last behavior you’ll create for now is the one of my personal favorites. This is a custom behavior that you can assign to a hotkey. When triggered, it transforms Xcode into what I refer to as Dev Mode, which is an optimized layout for developing your next masterpiece.

    To do this, create a new event by pressing the + button near the bottom left of the behavior preferences window. Name this behavior Dev Mode.

    Double-click the Command symbol (⌘) to the right of the event name, and then type Command . to define a hotkey.hotkey_assignment

    Next, configure the behavior with the following actions:
    DevModeBehavior

    Now whenever you press Command . you’ll be greeted with the same, clean development interface.

    This is the perfect time to introduce you to Xcode tab names, which work beautifully with behaviors.

    Xcode Tab Names: You can rename an Xcode tab simply by double-clicking on its title. This is rather a useless feature by itself, but becomes extremely powerful when you pair it with behaviors.

    In the second example above, when modifying the Pauses behavior, you named the tab Fix. This means that when the behavior is triggered, Xcode will use the Fix tab if it exists, or create a new tab if it’s not already there.

    Another example is the dual-screen Starts behavior. If a tab named Debug is open from a previous run, it’ll re-use it instead of creating a new one.

    You can create some very interesting behaviors by utilizing tab names in this manner.

    Okay, take a few minutes to play around with behaviors. Don’t worry, this tutorial will wait for you. :]

    Wait, are you back already? Okay, then it’s time for some action!

    Stats:
    Coolness points gained:400
    Total Coolness points:500
    Ninja points gained:50
    Total Ninja points:150

    Test Your Skills

    In the following sections, you’ll learn to put these tricks to a test, and learn some new ones while working on CardTilt.

    Build and run CardTilt, and you should see a screen like this:

    Run1

    Not what you’re seeing? Looks like it’s time for some ninja-level bug squashing!

    Locating the Bug

    It appears as though the app is having trouble loading the data, and it’s your job to fix it. Open CTMainViewController.m and enter Dev Mode (Command .).

    Notice these first few lines in viewDidLoad:

    self.dataSource = [[CTTableViewDataSource alloc] init];
    self.view.dataSource = self.dataSource;
    self.view.delegate = self;

    Looks like CTTableViewDataSource implements UITableViewDataSource and provides the table with data. Time to use your Xcode skills to confirm this and get to the bottom of the issue.

    Hold Command and click on CTTableViewDataSource to open CTTableViewDataSource.h in your primary editor. CTTableViewDataSource.m should’ve loaded in your assistant editor, as well. If that’s not the case, use the Jump Bar to change the assistant editor mode to counterparts like this:
    CounterpartsJumpBar

    Look around, and you’ll see members holds the data, and loadData loads it from the bundle. That looks like a great starting point for debugging. Switch CTTableViewDataSource.m to the primary editor by right clicking anywhere inside the assistant editor, and then choosing Open in Primary Editor.

    Below is an animation showing the steps you’ve taken thus far:

    SC1-Locatebug

    Ninja Dojo: For bonus ninja points, you can do all of the above without your mouse by following these steps:

    1. Press Command + Shift + O, typeCTMainViewController.m and then hit Enter to open the controller
    2. Enter Dev Mode (Command .).
    3. Place your cursor on CTTableViewDataSource and press Command + Control + J to jump to the definition.
    4. Change focus to the assistant editor by pressing Command + J, ->, then Enter.
    5. Bring down the jump bar tab by pressing Control + 4, then navigate to counterparts using arrows and Enter.
    6. Press Command + Alt , to open CTTableViewDataSource.m in the primary editor.
    7. Remember that being a ninja isn’t always the most efficient route, but you’ll always look cool.

      Bonus Ninja Tip: Open Quickly (Command Shift O) is one of the coolest Xcode ninja tools. Use it and love it.

    Stats:
    Coolness points gained:100
    Total Coolness points:600
    Ninja points gained:100
    Total Ninja points:250

    Fixing the Bug

    You need to determine if data made its way into members, so start by setting a breakpoint right below self.members = json[@"Team"]; and run the project.

    Note: If you are new to setting breakpoints and debugging in general, check out our video tutorial series on debugging.

    Of the behaviors you looked at earlier, Generates output will get triggered first, and then Pause follows immediately after. Because of the custom setup you created for Pause, you’ll get a new tab named Fix with a layout that is perfect for debugging! Now you have another cool trick to show your friends at your next party.

    Look at the variable inspector. Do you notice that self.members is nil a little, um, fishy. In loadData you can see that self.members is populated like this:

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    self.members = json[@"Team"];

    Dig into json in the variable inspector, so you can determine if the dictionary loaded correctly.

    You’ll see the first key in the data is @"RWTeam" instead of @"Team". When loading self.members, the key used the wrong data. Ah-ha! Eureka, there’s that little bug!

    To resolve, you need to correct the data in the source file:

  1. First, enter Dev Mode with Command ..
  2. Press Command + Option + J to jump to the filter bar and type this: teammember.
  3. Then, hold Alt and click on TeamMembers.json to open it up in the assistant editor.
  4. Finally, replace "RWTeam" with "Team".

This is how it looks when you follow these steps:

SC2-FixBug

Now remove the breakpoint, and then build and run. You should see this:

Run2

Much better, but it looks there is another bug. See how the descriptions below Ray and Brian’s titles are missing? Well, that’s a good thing because you’ll get to add more points to your coolness and ninja stats by resolving the problem.

Stats:

Coolness points gained:200

Total Coolness points:800

Ninja points gained:100

Total Ninja points:350

Speeding It Up

Let’s try to utilize more ninja tools for this second bug.

You probably know that UITableViewCells are configured in tableView:cellForRowAtIndexPath:, so navigate there using Open Quickly and following these steps:

  1. Press Command + Shift + O to bring up Open Quickly.
  2. Type in cellForRow, then press down once to select the instance in CardTilt.
  3. Hit Enter to open it in the primary editor.

Hold Command and click on setupWithDictionary to navigate to the definition. Look around a bit, and you’ll see some code that appears to be loading descriptions:

  NSString *aboutText = dictionary[@"about"]; // Should this be aboot?
  self.aboutLabel.text = [aboutText stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];

It’s loading the label from data found in dictionary[@"about"].

Now use Open Quickly to bring up TeamMembers.json. This time, open in the assistant editor by pressing Alt + Enter.

Check for the about key, and you’ll see someone misspelled it as aboot—probably a Canadian, like me! To fix this, use global Find and Replace. Sure, you could do this directly in the file, but using the find navigator is infinitely cooler.

Open up the find navigator and change the mode to Replace by clicking on the Jump Bar at the top. Type aboot into the find field and press Enter.
global_find

Hmm… there is one other place that uses the word aboot outside of TeamMembers.json.

No worries! Click on CTCardCell.m in the search results and press Delete. Now you no longer need to concern yourself with replacing it – cool!

Go to the replace field and type in ‘about’, and then press Replace All to finish the job.

Here’s how that looks in action:
SC3-Bug2

Ninja Dojo: This section already gave you tons of ninja points. To obtain even more, you can use Command + Shift + Option + F to open the Find navigator in replace mode.

If that’s a tad too ninja, you can use Command + Shift + F to open up the find navigator in Find mode and change the mode to Replace afterwards.

If that’s still too ninja, you can use Command 3 to open up the Find navigator and go from there!

Ninja Tip: There are many, many ways to perform actions in Xcode. Play around and find the way that suits you best :]

Build and run. You should now see all the cells properly loaded, like this:
Run3

Stats:
Coolness points gained:200
Total Coolness points:1000
Ninja points gained:50
Total Ninja points:400

Keeping Your Designer Happy

That’s it for debugging today. Give yourself a round of applause and pat on the back for getting the app up and running.

Before you go and show it to someone, you want to make sure the app’s interface is flawless. Especially if that someone is your designer, who likes to take his ruler to the screen.

This section will show you a few tricks in Interface Builder to achieve such perfection, and of course, help you become even cooler in the process.

Open up MainStoryboard.storyboard. Usually, you want the standard editor and the utilities area open when working in interface builder, so create a new custom behavior for this called IB Mode. Feel free to use the version below, but try to create your own before you look at the solution used to create this tutorial. It’s cool to be different!

Solution Inside: IB Mode SelectShow>

You can see that I used Command Option . as the hotkey for IB Mode.

Now that you’re looking at a comfy Interface Builder, take a look at CTCardCell. First, you want to center mainView inside Content View. Here are two tricks make this relatively elementary:

Hold Control + Shift and left click anywhere on mainView within the editor.
You’ll see a popup that lets you choose between all the views under your mouse pointer like this: IBPopup

This allows you to select mainView easily, even though cardbg is blocking it.

Once you select mainView, hold Alt and move your cursor around the edges of Content View to see the spacing of the view.

Here’s how that looks:
SC4 - IB1

Turns out the alignment isn’t much to behold. That’s not very ninja!

To fix this, you’ll need to resize the view. turn on Editor\Canvas\Live AutoresizingTo force subviews to re-size when you resize their parent view. Now drag the corners of mainView while holding Alt and adjust until there are 15 points on each side.

Dragging to a very granular level can be tricky, and you may need to play around with different resize handles, as seen in the video replay below. In many cases, it’s preferable to use the Size Inspector to modify spacing on complex layouts rather than wrestling with your mouse.

SC5-IB2
Try using the same trick to help align the three labels titleLabel, locationLabel and aboutLabel so that they have zero vertical spacing between them. Hold Alt to monitor the spacing while repositioning the labels with the arrow keys or your mouse.

Did you notice the left edges of these labels are also misaligned?

Your designer will definitely want them to be left-aligned with nameLabel and webLabel. To accomplish this easily, you’ll use a Vertical Guide.

Select cardbg and go to Editor\Add Vertical Guide. Take note of the hotkeys, they’re Command - for horizontal guide and Command | for a vertical guide.

Those two hotkeys probably make the most visual sense–ever.

Once you have the vertical guide on the screen, drag it to 10 points from the left edge of cardbg. Now views can snap to this vertical guide and align perfectly. Go ahead and line up those labels.

OK, so Xcode isn’t always perfect, and you may occasionally have issues selecting a guideline right after you create it.

If hovering over it doesn’t work, quickly open a different source file and then flip back to the storyboard. Once it reloads the storyboard, the issues typically resolve themselves.

Bonus Ninja Tip: The best part about vertical and horizontal guides is that all views can snap to them, they don’t have to be in the same hierarchy to align nicely!

Here is a replay of the steps to correct alignment in this scene:
SC5-IB2

I bet you can’t wait to show your work to your designer now!

Stats:

Coolness points gained:400

Total Coolness points:1400

Ninja points gained:0

Total Ninja points:400

Above and Beyond

Now that you have a functional app and a happy designer, now you just need to do a little code cleanup.

Use Open Quickly to open CTCardCell.m – you should know how by now! Remember to enter Dev Mode as well.

Just look at that messy list of @properties at the top of CTCardCell.m:

@property (weak, nonatomic) IBOutlet UILabel *locationLabel;
@property (strong, nonatomic) NSString *website;
@property (weak, nonatomic) IBOutlet UIButton *fbButton;
@property (weak, nonatomic) IBOutlet UIImageView *fbImage;
@property (strong, nonatomic) NSString *twitter;
@property (weak, nonatomic) IBOutlet UIButton *twButton;
@property (weak, nonatomic) IBOutlet UILabel *webLabel;
@property (weak, nonatomic) IBOutlet UIImageView *profilePhoto;
@property (strong, nonatomic) NSString *facebook;
@property (weak, nonatomic) IBOutlet UIImageView *twImage;
@property (weak, nonatomic) IBOutlet UILabel *aboutLabel;
@property (weak, nonatomic) IBOutlet UIButton *webButton;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

In this section, you’re going to create a custom service to run the shell commands sort and uniq on blocks of code like this.

Note: If you’re not familiar with these shell commands, they’re quite self-explanatory. sort organizes the lines alphabetically, and uniq removes any duplicate lines.

uniq won’t really come in handy here, but is handy when you’re organizing #import lists!

Mac OSX allows you to create services you can access throughout the OS. You’ll use this to create a shell script service to use in Xcode.

Follow these steps to set it up:

  1. In OSX, search for Automator using Spotlight and open it
  2. Go to File\New and choose Service
  3. In the Actions filter bar, type in shell and double-click on Run Shell Script
  4. In the bar above the newly added service, check Output replaces selected text
  5. Change the contents of the script to sort | uniq
  6. Press Command S and save your new service as Sort & Uniq

Here’s what the final window looks like:
SortnUniqSS

Now Go back to Xcode and select that messy block of @properties in CTCardCell.m. Right click on the selected code and go to Services -> Sort & Uniq and watch how tidy that rowdy list becomes. You can watch the magic on the big screen here:
SC6-SortUniq

Now that is worth at least 800 coolness points.

Stats:

Coolness points gained:801

Total Coolness points:1801

Ninja points gained:0

Total Ninja points:400

Code Snippets

That marks the end of basic ninja training and your task of debugging CardTilt – congratulations on getting here! I hope you’ve learned and feel more cool and ninja-like.

Surely, you’re eager to learn even more tricks. Fortunately for you, there is one last trick to share.

You have likely used Xcode’s Code Snippets before. Some common ones are the forin snippet and dispatch_after snippet.

In this section, you’ll learn how to create your own custom snippets and look extremely cool as you re-use common code blocks.

The code snippet you’ll create is the singleton accessor snippet.

Note: If you’re not familiar with the singleton pattern, you can read all about it in this great tutorial.

Below is some boilerplate code you’re likely to use frequently with this pattern:

+ (instancetype)sharedObject {
  static id _sharedInstance = nil;
  static dispatch_once_t oncePredicate;
  dispatch_once(&oncePredicate, ^{
    _sharedInstance = [[self alloc] init];
  });
  return _sharedInstance;
}

What’s also cool is that this snippet includes the dispatch_once snippet.

Create a new class in CardTilt called SingletonObject and make it a subclass of NSObject. You won’t actually it for anything, except for as a spot from which to drag code to create a snippet.

Follow these steps:

  1. Paste the code above into SingletonObject.m, just below the @implementation line
  2. Open the Code Snippets Library using Command Option Control 2. You should see the library of code snippets that are included in Xcode by default
  3. Select the entire +sharedObject function and drag it into the library

Note: If you’re having issues dragging code, click on the selected code and hold for a second before starting to drag.

Here is what this looks like:
snippet

Your new code snippet will automatically show up at the very bottom of the library. You can use it by dragging it from the library into any file – go try it out!

Now double-click on your newly created snippet and press edit.

The fields that display in this popup are particularly useful; in fact they are so valuable that each deserves and explanation:

  • Title and Summary: The name and description of the snippet that displays in the library and during completion.
  • Platform and Language: The platform and language that this snippet is compatible with.
  • Completion Shortcut: The code completion shortcut you can type in Xcode to this snippet.
  • Completion Scopes: The scope in which this snippet should be available via code completion. This is great for maintaining a clean snippet library.

Fill in the properties like this:
SS-Snippet

Tokens

Snippets become especially powerful when you add Tokens because they allow you to mark code in the snippet that shouldn’t be hard-coded. It makes them very easy to modify using the Tab key, much like as it is with auto-completed methods.

To add a token, simply type <#TokenName#> in your snippet.

Create a token for the Object part of your sharedObject snippet by replacing sharedObject with shared<#ObjectName#> so it looks like this:

SS-Snippet2

Save the snippet by hitting Done and give it a spin.

Type singleton accessor in the SingletonObject implementation file and use the autocomplete when it shows up.
SC7-Snippet

Custom code snippets like this can become very powerful for frequently used patterns. Learning these last few tricks is definitely worth some extra points!

Stats:

Coolness points gained:50000

Total Coolness points:51801

Ninja points gained:2000

Total Ninja points:2400

Where to Go From Here

Congratulations on achieving such a high score!

To sum it up, here’s what you’ve learned and done as you’ve worked through this tutorial:

  1. Modified the layout of Xcode using hotkeys.
  2. Made Xcode change its layout for you based on behaviors you defined.
  3. Made use of the assistant editor.
  4. Learned to use Open Quickly to navigate through Xcode.
  5. Deleted results from the Find navigator.
  6. Made your designer happy by aligning views in the Interface Builder with guides and hotkeys.
  7. Created a Mac OSX service to use in Xcode.
  8. Created and used custom code snippets.
  9. Most importantly, you learned how to become an Xcode ninja.

That was all pretty easy, now wasn’t it? Think of all the cool tricks you have to show your friends and family now! They’ll no doubt completely understand your excitement ;]

There are still plenty of other ways you can improve your Xcode efficiency and up your own personal coolness and ninja factors. A few of them are:

The next step is to go and put your newfound ninja skills to use!

I hope you enjoyed this tutorial. If you have any questions, comments or would like to share a cool trick you know, make sure to leave a comment below!

Supercharging Your Xcode Efficiency is a post from: Ray Wenderlich

The post Supercharging Your Xcode Efficiency appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4370

Trending Articles