Objectively Speaking: A Crash Course in Objective-C for iOS 6

Note from Ray: This tutorial is now fully up-to-date for iOS 6, and uses Modern-Objective-C syntax. Here’s the pre iOS 6 version if you need it! This is a post by iOS Tutorial Team Member Linda Burke, an indie iOS developer and the founder of canApps. Are you a software developer skilled in another platform, […] By .

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 5 of this article. Click here to view the first page.

Hooking Up a Control

To see it all in action, open up MainStoryboard.storyboard. Next, look for the right sidebar in your Xcode window. If you don’t see one, you might need to use the rightmost button under the Views section, on the toolbar at the top, to make the right hand sidebar visible.

The lower part of the righthand sidebar has four tabs, which you can switch between using the icons at the top of that section. The section you want is the Object Library.

From the Object Library, drag a Text View control and a Round Rect Button onto the view. Position them to your liking. Add a title to the button, such as “Quote”. Change the color and font for the controls as you see fit. You can change most properties for the controls via the upper part of the right hand sidebar which too has several tabs that you can switch between – the one you’ll use the most to customise the appearance of the controls is the Attributes Inspector tab.

Storyboard layout for Objective-C tutorial

As the text field is for display only, untick Behavior – Editable.

Now you need to link the button and the text view to the outlet and action you already set up in your class.

Link your text view by control-clicking the View Controller in the left sidebar, and dragging to the text view. Release, and select quoteText from the popup that appears.

Connecting the text view to the outlet

Alternatively, you can simply select the view controller in the left sidebar and then switch the top portion of the right hand sidebar to the Connections Inspector tab. You should see all the connections available for your View Controller. You can now simply drag from the available connection to the control visible on screen.

Connections Inspector

Remember the reason why the Storyboard knows about your quoteText property is because you added the IBOutlet keyword earlier!

Hooking Up an Action

Hooking up an action on a control (such as a button tap) to a method is quite similar to the process of hooking up a control to a property.

This time, control-drag from the button up to the View Controller, release, and choose quoteButtonTapped: from the popup:

Hooking up an action to a method

Alternatively, you can simply select the button, and if you have the Connections Inspector selected in the right hand sidebar, you’ll notice that you get a list of events for the button. You can drag from Touch Up Inside event to the View Controller there as well.

Let Her Rip!

Guess what? You’re ready to rock ‘n’ roll. Simply click on the Xcode Run button (the first button at the top of the screen) to compile and run your app in the simulator.

If there are errors, don’t panic. At this stage, they should be self-explanatory. Often just typos when declaring your variables. Remember, Xcode is case-sensitive.

If your app does compile and run, then click on the Quote button to get a random quote:

Allright – you have a functional app, and you’ve learned a ton about Objective-C already – you’ve created properties, your own method, made use of classes, and tons more!

But wait – there’s more! Right now your list of quotes are hard-coded into the app. Wouldn’t it be a lot better if you could load them from an external file?

Ah, the joys of property lists are about to be revealed!

Property Lists Rule!

A property list is a special XML format defined by Apple that are designed to store basic data types like strings, numbers, arrays, and dictionaries. They are very easy to create, and to read and write from code, so they are a great way to get in small bits of data into your app.

Let’s try this out! Create a new file by right-clicking on your project root on the left sidebar (the Project Navigator) and selecting New File. Then select the iOS\Resource\Property List template and click Next. Select the location to save your new file (usually somewhere within the project folder for the tutorial project) and name the file quotes.plist.

You can either edit the property list file from within Xcode in a grid-view (as a list of properties) or as a text file. If you want to edit as a text file, right-click on the quotes file on the Project Navigator and select Open As\Source Code.

Since you want to quickly add all the quotes by copying and pasting, opening as source code probably would be the faster route. If you want though, you can try the grid view approach and try to figure out how to add the same values as below using that method.

Now, add your movie quotes by copying and pasting the following into quotes (in source code mode):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!--
 Quotes
 -->
<plist version="1.0">
    <array>
        
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>Frankly my dear, I don't give a dam.</string>
            <key>source</key>  <string>Gone with the wind</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>Here's looking at you kid.</string>
            <key>source</key>  <string>Casablanca</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>There's no place like home.</string>
            <key>source</key>  <string>Wizard of Oz</string>
        </dict>
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>Play it again sam.</string>
            <key>source</key>  <string></string>
        </dict>
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>Elementary my dear Watson.</string>
            <key>source</key>  <string>Sherlock Holmes</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>Fasten your seatbelts. It's going to be a bumpy night.</string>
            <key>source</key>  <string>All about Eve</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>I have not the pleasure of understanding you.</string>
            <key>source</key>  <string>Pride and Predice</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>O Romeo, Romeo! wherefore art thou Romeo?</string>
            <key>source</key>  <string>Romeo and Juliet</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>To be or not to be</string>
            <key>source</key>  <string>Hamlet</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>...Crime is only a left-handed form of human endeavor.</string>
            <key>source</key>  <string>The Asphalt Jungle</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>That's, uh, quite a dress you almost have on...What holds it up?</string>
            <key>source</key>  <string>An American in Paris</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>classic</string>
            <key>quote</key>  <string>Love, desire, ambition, faith - without them life is so simple, believe me</string>
            <key>source</key>  <string>Invasion of the Body Snatchers</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>Go ahead make my day.</string>
            <key>source</key>  <string>Dirty Harry</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>May the Force be with you.</string>
            <key>source</key>  <string>Star wars</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>Hasta la vista, baby</string>
            <key>source</key>  <string>Terminator</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>I feel the need for speed.</string>
            <key>source</key>  <string>Top Gun</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>She doesn't even go here.</string>
            <key>source</key>  <string>Mean Girls</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>It takes a great deal of bravery to stand up to your enemies, but a great deal more to stand up to your friends.</string>
            <key>source</key>  <string>Harry Potter</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>I solemnly swear that I am up to no good.</string>
            <key>source</key>  <string>Harry Potter</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>You like pain? Try wearing a corset.</string>
            <key>source</key>  <string>Pirates of the Carribean</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>Houston, we have a problem.</string>
            <key>source</key>  <string>Apollo 13</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>I'll be back.</string>
            <key>source</key>  <string>The Terminator</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>E.T. phone home.</string>
            <key>source</key>  <string>E.T.</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>Why are you trying so hard to fit in when you were born to stand out?</string>
            <key>source</key>  <string>What a girl wants</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>Watch you talkin about Willis?</string>
            <key>source</key>  <string>Different Strokes</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>The plane, the plane</string>
            <key>source</key>  <string>Fantasy Island</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>D'oh</string>
            <key>source</key>  <string>The Simpsons</string>
        </dict>
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>Kids, you tried your best and you failed miserably. The lesson is, never try.</string>
            <key>source</key>  <string>The Simpsons</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>You don’t win friends with salad.</string>
            <key>source</key>  <string>The Simpsons</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>Whoever said that money doesn't buy happiness didn't know where to shop.</string>
            <key>source</key>  <string>Gossip Girl</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>If I were you, I'd accessorize with some gloves. Even a manicure can't mask those peasant hands.</string>
            <key>source</key>  <string>Gossip Girl</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>I tried to be diplomatic, but mostly I just lied a lot.</string>
            <key>source</key>  <string>Twilight</string>
        </dict>
        
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>Once people start throwing wet stuff, I go inside.</string>
            <key>source</key>  <string>Twilight</string>
        </dict>
        
        <dict>
            <key>category</key>  <string>modern</string>
            <key>quote</key>  <string>I don’t like to lie – so there’d better be a good reason why I’m doing it..</string>
            <key>source</key>  <string>Twilight</string>
        </dict>

    </array>
</plist>

These are just a few quotes to serve as examples. Have some fun and add your own favorites. If you’re feeling lazy, the sample project has a property list of many quotes.

The quotes are categorized as either classic or modern to illustrate a really neat feature that we’ll get to a bit later.

You can also switch over to the Property List view (right-click on the quotes file on the Project Navigator and select Open As\Property List) to see how the values you added look in the grid view and how it is organised. Now that you know how the different editing modes work, you can always switch back and forth as you like.

Property lists are cool, but can be very uncool when you get an error. Common mistakes for newbies are forgetting the end tag or accidentally deleting a < or >. If your property list doesn’t load, then you’ll need to trawl through and work out why. Earlier versions of Xcode gave line numbers for errors. I think it was from version 4 onwards that this helpful feature was excluded.

If you really get stuck, you need to methodically go through your file. I do this (a bit too often to be frank) to make it easier: copy my plist file, then remove chunks a bit at a time to identify the approximate location of the error.

Having created your lovely property list, you are now ready to load it into an array for use. So let’s switch back to ViewController.m and add the following to the end of viewDidLoad:

// 2 - Load movie quotes
NSString *plistCatPath = [[NSBundle mainBundle] pathForResource:@"quotes" ofType:@"plist"];
self.movieQuotes= [NSMutableArray arrayWithContentsOfFile:plistCatPath];

It’s as easy as that – now you have an array with all of the movie quote data you entered in the property list!

To try out your new array, you might think that all you really need to do is change getting the random quote from your personal quotes array to the movie quotes array. So, in quoteButtonTapped: you simply replace all references to myQuotes with movieQuotes, right?

But that alone will not work, as you will find if you try it. This is because myQuotes was an array of quote strings. But movieQuotes is not an array of strings. Instead, it’s an array of dictionaries where a dictionary is a list of values where you can access each value based on a unique key.

Why? Because that’s how you set up the property list (go look at it again to see!)

Note: Dictionaries are key/value stores, similar to hashtables in other languages. You can look up entries in a dictionary with the valueForKey method.

So replace quoteButtonTapped with the following code which switches over to using the movieQuotes array but also gets the quote by using the right key for each quote dictionary:

-(IBAction)quoteButtonTapped:(id)sender {
    // 1 - Get number of rows in array
    int array_tot = [self.movieQuotes count];
    // 2 - Get random index
    int index = (arc4random() % array_tot);
    // 3 - Get the quote string for the index
    //NSString *my_quote = [self.myQuotes objectAtIndex:index];
    NSString *my_quote = self.movieQuotes[index][@"quote"];
    // 4 - Display the quote in the text view
    self.quoteText.text = [NSString stringWithFormat:@"Quote:\n\n%@",  my_quote];
}

Keep the commented out line in section #3 as it will come in handy later. Build and run and enjoy your new movie quotes!

Movie Quotes

Awesome, now you have a file that can read quotes from an external file! This can be especially handy if you want someone else to fill in some quotes for you as you continue to work on your app.

Next you’re going to get a bit fancy and allow the user to select between viewing myQuotes or movieQuotes, and whether to view classic or modern movie quotes.