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 2 of 5 of this article. Click here to view the first page.

Manual Labor

Now you can store your favorite quotes in the myQuotes array. You’ll do this in viewDidLoad, which is the method that executes when the view (screen) is first created.

In viewDidLoad, add the following code after [super viewDidLoad];. Include your own favorite quotes if you like. This is the “manual labor” approach and is quite okay for a small number of array entries.

// 1 - Add array of personal quotes
 self.myQuotes = @[
                     @"Live and let live",
                     @"Don't cry over spilt milk",
                     @"Always look on the bright side of life",
                     @"Nobody's perfect",
                     @"Can't see the woods for the trees",
                     @"Better to have loved and lost then not loved at all",
                     @"The early bird catches the worm",
                     @"As slow as a wet week"
                     ];

Here you are setting the myQuotes property to a list of quotes. There’s some funky syntax you might not be used to here, so let’s break it down.

  • self is a special keyword that means “this current class” – kind of like this in other programming languages.
  • You can access properties on the class by using a dot, and then typing the name of the property – i.e. self.myQuotes lets you access the myQuotes property you created earlier.
  • To create an array, there’s a handy new shortcut in Objective-C – @[ item1, item 2, item 3 ].
  • Each item in the array is a string. To create strings in Objective-C, you need to prefix them with the @ symbol. If you’re used to other languages, this can be easy to forget, which will probably cause your app to crash :] So if your app crashes when it uses a string, double check you remembered to use the @ symbol!

Great – now you have an array of quotes ready to go. It’s time to add some code that will allow you to display a random quote on the screen!

Going to the Outlets

You haven’t created the user interface yet, but when you do you’ll be adding a text view to show the quote, and a button to tap to get a random quote.

To display a random quote to the screen, you’ll need two things – a reference to the text view so you can set the text appropriately, and notification when the button is tapped.

But how do you connect what goes on in the interface with your code? Through some special keywords – IBOutlet and IBAction!

Let’s see how this works, starting with an IBOutlet. Add the following to ViewController.h under the arrays:

@property (nonatomic, strong) IBOutlet UITextView *quoteText;

Here you declare a property just like before (for a UITextView class), but you mark it with a special keyword – IBOutlet.

IBOutlet means that quote_text is an object that can be linked to an interface element on the XIB file so that the view controller can access (or change) properties of the interface element. In this case, we’ll be setting the displayed text for the UITextView control but you could just as easily change the color, font, size, etc.

Next, add the following line of code after the list of properties:

- (IBAction)quoteButtonTapped:(id)sender;

This defines a method that you will implement in this class. This is the first time you’ve seen a method defined in Objective-C, so let’s go over it bit-by-bit:

  1. First you put a dash , which indicates you are defining an instance method.
  2. Then you put the return value of the method. This particular method returns an IBAction, which is actually defined to void – i.e. the method returns nothing. But IBAction has another special property – it marks the method as something to you can connect to an action on a UI element. In this case, you’ll be hooking things up so when the button gets tapped, this method gets called.
  3. Next you put the name of the method – quoteButtonTapped in this case.
  4. Then you put a colon, and in parenthesis put the type of the first parameter. id is a special type that means “any object that derives from NSObject”. Usually when you set up callbacks that buttons and other controls will call, they pass whatever button/control is sending the callback as the first parameter. Since you don’t necessarily know what type it is, you put id here.
  5. Then you put the name of the parameter – sender in this case.

If you had more than one parameter, you would just repeat steps 3-5 multiple times. The syntax of naming methods is a little strange in Objective-C, but you’ll like it when you get used to it.

Next, switch to ViewController.m to add the implementation of quoteButtonTapped:. Add this to the end of the file (but above @end):

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

Let’s go over this line by line:

  1. First you get the count of items in an array. This is the first example you’ve seen of calling a method in Objective-C. The syntax is a little strange – you put a bracket ([), then the name of the object you’re calling the method on (self.myQuotes), then the name of the method you’re calling (count). Finally, you end the method call with a close bracket (]). Note this method doesn’t take any parameters – you’ll see an example that does in step 4.
  2. Next you use the arc4random function to generate a random number. arc4random() is a regular C-style function (not a method), so you use the regular parenthesis syntax you know and love. In this case, since you want to randomly select one of the quotes, the highest possible value is the number of rows in the array, and the lowest possible value is 0. In Objective-C (like many other languages), the first row in an array is row 0, not 1.
  3. Next you look up an item in myQuotes. Objective-C’s new literal syntax allows you to access elements in an NSArray by simple subscripting like you can see here.
  4. Finally, you use stringWithFormat method to format the final output string so that you can display a label and add a new line before displaying the quote. It uses variable substitution, like printf in C/C++. %f is float, %d is integer, and %@ is Objective-C object.

Now in order to actually see the quote on the screen, you need to link the text field outlet in the class with a text field control in your XIB file.