Objectively Speaking: A Crash Course in Objective-C
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, but want to start learning iPhone development (and hence Objective-C)? This was my situation not so long ago, and frankly, I’d gotten a bit rusty from […] By .
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Objectively Speaking: A Crash Course in Objective-C
40 mins
We Have Lift Off!
To see it all in action, open up ViewController.xib. 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.
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 right-clicking the text view, clicking on the New Reference Outlet circle, dragging to File’s Owner and selecting quote_text.
Alternatively, you can simply select File’s Owner 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 File’s Owner, which happens to be your controller class. You can now simply drag from the available connection to the control visible on screen.
Now, you can programmatically set the value for the text displayed in the text view by modifying quote_text.
Similarly, we can hook up touch events on the button we added to the XIB file to the quote_btn_touch action we set up earlier. To do that, right-click on the button and drag Touch Up Inside to Files’s Owner and select quote_btn_touch.
Alternatively, you can simply select the button in the XIB view, 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. Now drag from the Touch Up Inside event to the File’s Owner and you should get a list of possible actions you can connect that event to. Just select the one you want.
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. Not having many quotes in the list limits the excitement a little. But don’t worry, you’re about to load up another array and with this one you can go wild and add as many quotes as you like, because they won’t be in the code.
“How so?” you ask?
Ah, the joys of property lists are about to be revealed! I’m a big fan of property lists.
Property Lists Rule!
Create a new file with the iOS\Cocoa Touch\Objective-C class template. Name the class SMNote, and make it a subclass of UIDocument.
Create a new file by right-clicking on your project root on the left sidebar (the Project Navigator) and select “New File …” Then select iOS\Resource\Property List 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”.
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 we 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//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>category</key> <string>classic</string>
<key>quote</key> <string>Frankly, my dear, I don't give a damn.</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>The 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>Casablanca</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>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 2: Judgement Day</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 and the Sorcerer's Stone</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 and the Prisoner of Azkaban</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 Caribbean</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] copy];
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 quote_btn_touch 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.
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 quote_btn_touch 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)quote_btn_touch:(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 objectAtIndex:index] valueForKey:@"quote"];
// 4 - Display the quote in the text view
self.quote_text.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!
Now 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.