Now that you’ve gotten your feet wet from programming your first two iPhone and iPad apps, I want you to tell yourself that you have to keep on truckin’ with more apps and more practice. You need to create a more natural connection between the synapses in your brain.
Initially, many of my computer science colleagues had disdain for my approach of blindly hauling newbie programmers through code without explaining it all. Over the years, I’ve learned exactly when to tell you what’s going on and when to just jostle you through the code. Most importantly, you need to keep on truckin’ and keep your brain dialed into Xcode.
The third Hello World app introduces you to user interaction and if-else statements, which results in slightly more complex code. Remember, this is Objective-C—a pretty complex and difficult language—so I explain only what I deem necessary. That brings up one difference between Chapters 2 and 3. In Chapter 2 we did not repeat enough actions for you to make your own associations.” Well, here in Chapter 3 you will make these associations and therefore it will be appropriate to start digging the code.
So let’s get on with the next application. When it’s done, take a break and then be ready to go back and review lines of your input, as you focus on certain portions of the code and see how it all works together.
Note Besides the information I present here in this book, including various screenshots, I also offer screencasts on my website. Go to rorylewis.com, click the iOS 6 Tutorials icon, and then click either Video tutorials or Downloads for this book.
helloWorld_03: An Interactive Single View App
In the first two programs you did by yourself, helloWorld_01 and helloWorld_02, you said hello to the world using a Single View platform that housed a button. This third app will also be a Single View Application, but with a little more complexity. In your third app, the user is asked whether he’s a geek. When he taps the Are you a Geek? button, teasing text will appear. First it says, “You Are!” When the user taps it again, it says, “Shut up you’re not!”
Before you get started with the next method, save helloWorld_01 and helloWorld_02 in a folder of your choice that is not on the desktop. Create a folder in your Documents folder called My Programs and save the file named helloWorld_01 there by dragging the entire folder inside your My Programs folder. Now, with a fresh, clean, empty desktop, close all other programs you may have running by selecting programs. Press +Tab and then +Q to close everything until only the Finder is left on your screen.
Figure 3-1. Open Xcode, select the Single View Application template, and click Next
Figure 3-2. Name your project, make sure it’s for an iPhone, and then click Next
Figure 3-3. Drag a picture of yourself from the desktop into your Supporting Files folder
Figure 3-4. Complete importing your image by selecting the “Copy items into destination …” option and clicking Finish
Note I can hear you asking, “Why even give us this option, then?” Here’s a simple answer that covers most but not all bases: Let’s say you were designing a game or program that has a database of millions and millions of files, and this database was too large to fit on an iPhone or iPad. Here, you would not check the “Copy items” box. You would allow the pointer reference dude to say, “Yo, I take no responsibility for any of this, it’s not really here, it’s at this URL located at www.wherever.com.”
Okay, now you’re ready to start dragging and dropping items onto your View Design area, which is what the user sees when she looks at her iPhone.
Figure 3-5. Open your nib file
Figure 3-6. Open the Object Library
Figure 3-7. Drag a UIImageView onto your View Design area
Figure 3-8. Associate your selected image with your UIImageView
Figure 3-9. Drag a label onto your View Design area
Figure 3-10. Center, change color, and delete the label text
Figure 3-11. Drag in a button and center it toward the upper portion of your View Design area
Figure 3-12. Double-click the button and enter your text
Connecting to the Code
You’re done with dragging objects from the Library to the View Design area. It’s time to connect these objects to your file’s owner, so you can associate it with code.
Figure 3-13. Hide the Utilities Inspector and open the Assistant Editor
Note You can also use keyboard shortcuts to open the Assistant Editor (Option++Return) and the Standard Editor (+Return). There are thousands of keyboard shortcuts; some achieve superstardom, and some never make it out of books and blogs.
Figure 3-14. Control-Drag a connection from your button in Interface Builder directly into your header file
Figure 3-15. When the button’s connection dialog appears, specify what type of connection you plan to use in your code
Figure 3-16. Name your button button
Figure 3-17. Control-drag from the label into your header file
Figure 3-18. When the label’s connection dialog appears, specify what type of connection to use in your code and name it label
Figure 3-19. Header code is written without typing
-(IBAction)button: (id)sender; //This creates an action for a button (see details below)
IBOutlet UILabel *label; //This adds an outlet to a label, just as you did in previous examples.
Digging the Code: -(IBAction)button: (id)sender;
After changing the button from outlet to action, as shown in Figure 3-15, you still need to name it. In Figure 3-16, it’s named button. Let’s talk about this code briefly. Don’t worry if you space out.
When you made the button an action, you created something that is critical to know: you created a method, and you could have named it monkey if you wanted to. If you did, it would look like this:
- (IBAction) monkey :(id)sender;
I only want you to know two things about this method you called monkey. First, it has a return type. Second, it has an argument.
- (IBAction) monkey:(id)sender;
- (IBAction)monkey: (id)sender;
Now, take a nice deep breath. You’re done peeking under the hood for a while. You’re also done with the header file, and now you can move on to the implementation file.
Setting up the Coding Environment
Before typing code, you need to do a little more housework. You need to set up your working environment.
Figure 3-20. Close the Assistant Editor and open the Standard Editor
Figure 3-21. Save everything
Figure 3-22. After saving, open your ViewController’s header file
Creating a Programming Roadmap
You’re now ready to get into some code that does something useful.
Figure 3-23. Create a Boolean variable
- #import <UIKit/UIKit.h>
bool ruaGeek;
@interface ViewController : UIViewController
- (IBAction)button:(id)sender;
@property (retain, nonatomic) IBOutlet UILabel *label;
@end
Figure 3-24. Open the implementation file
Figure 3-25. Make some space between the button’s squiggly brackets
Figure 3-26. Open the Code Snippet Library
Figure 3-27. Select the If-Else Statement snippet
Figure 3-28. Drag the snippet into place
if ( First Condition ){Do this } else {Do that )
if (<# condition #>) { <#statements-if- true #> }
else {
<#statements-if- false #>
}
You want to replace the <#condition#> with the Boolean variable you declared in the header file ruaGeek. You want to first set the state of ruaGeek to be true and then have your app say one thing. Then set the state of ruaGeek to false and have it say another thing. Easy! Let’s set the variable to true and test for this condition; type ruaGeek==true, as shown in the following code and in Figure 3-29 and completed in Figure 3-30.
Figure 3-29. Make some space between the button’s squiggly brackets
Figure 3-30. Make some space between the button’s squiggly brackets
Pseudo code: setting ruaGeek to be true for the initial condition:
if ( ruaGeek==true ) { <#statements-if- true #> }
else {
<#statements-if- false #>
}
}
if (ruaGeek==true) {
label.text=@”Shut up! You’re not!”;
ruaGeek=false;
} else {
<#statements-if-false#>
}
Now, rather than typing everything again for the else part, copy what you just coded and paste it into the second condition, as shown in Figure 3-30.
Figure 3-31. Set the initial condition to true
Figure 3-32. Let’s run it!
In the real world, clients always want you to change everything around, so get used to this. Making changes also helps you learn what you just did. When I ran it, I saw two errors, seen in my video. Yours may not have had one of them, but let’s go back and tweak the code a little.
Figure 3-33. Swap out the if statements
if (ruaGeek==true) {
label.text=@" You are ";
ruaGeek=false;
} else {
label.text=@" Shut up! You’re not! ";
ruaGeek=true;
}
Figure 3-34. Wow, talk about Geek power!
Digging the Code
In the following reviews, I go over some of the code from this chapter, referencing familiar code and explaining the processes in more detail. I introduce you to more technical terms that you’ll use in future chapters and in communicating with other programmers.
Consider this analogy: In helloWorld_01 and helloWorld_02 I taught you how to get into a car, turn the ignition, press the accelerator, and steer as you moved forward. In helloWorld_03, I guided you with similar directions, but as you drove toward your destination, I explained how the car is a hybrid engine and that it has some gasoline components and some electrical components. We talked about methods, outlets, and actions.
Now you’ve arrived at your destination; you’ve completed helloWorld_03. I’m about to open the hood and show you how, when you pressed the accelerator, it either pumped gasoline into the engine or used the electric motor. Under the hood, I’ll show you where these components are located. And by the time you finish this book, looking under the hood and digging the code, I will have described the amount of gasoline being squirted onto the pistons by the carburetors, the exact torque and heat emission of the electric motor, and so on. And guess what—you’ll be able to handle it!
One last comment about this section that is really important: “Digging the Code” is a section that I encourage you to read without definitive understanding. It’s okay if you only partially “get it.” Of course, if you happen to attain full comprehension of the subject in all its details, well, that’s great. What I suggest, though, is that you read these sections at the end of each chapter loosely because:
Note that my research is in neurological acute brain injuries, where I study the brain and neural interconnectivity. This methodology of first connecting neurons and then infusing the deeper connective associations when the brain is relaxed is one that I’ve developed over the years. So, I want you to consider my former readers’ and students’ opinions about this matter and absorb my theorem concerning neurological leaps.
Note Becoming an eloquent, knowledgeable, and financially thriving coder takes neurological leaps, during states wherein your brain is open to absorbing new data without the hypothalamus releasing anxiety hormones that pollute the ability of your neurons to create new connections, which allows linking logic and code to ontological reasoning.
So Zen out, zone out, and read in a meditative state with no fear. When that voice says, “You’re not understanding it all,” say, “That’s okay, Dr. Lewis said so, now go away!” You will Zen and zone through the following:
Back in Figure 3-5, I instructed you to open your nib file. You could see that it was written xib, and to make it more confusing, some coders call them “zib” files. Just ignore them. Refer to xib files by pronouncing them as “nib.” At the recent 360iDev for iPhone Developers Conference in Denver, it was clear most of the presenters referred to xib files as “nibs,” not “zibs.” But no matter how you refer to them, it’s important that you understand what’s going on with these files. What are they? Do we need them? Do you need to know how they work?
Do you recall, from step 5, Figure 3-5, how you opened Interface Builder View when you clicked on that nib file? It was here that you saw, for the second or third time, your view and began dragging and dropping items onto your View Design area. What’s going on here?
It turns out that when you examine nib files at the level of Objective-C, you see that they contain all the information necessary to activate the user interface (UI) files, transforming your code into a graphical iPhone or iPad work of art. It’s also possible to join separate nib files together to create more complex interactions, as you’ll see later in this book. But to follow along, you need to add two words to your vocabulary: Instances and Instantiation.
Note You’ll be manipulating these arms and legs to do cool stuff in apps and selling them on the iTunes store.
You’ve created an instance of something when you’ve told the computer how and when to grab some memory and set it aside for some particular process or collection of processes such that, when the parameters are all met, the user has an experience of this data (that is, whatever was assigned in memory). Sometimes we refer to these collections or files of descriptions and commands as classes, methods, or objects. In this code-digging session, these terms might seem to run together and appear as synonyms, but they’re not. As you read on, you’ll come to understand each term as a distinct coding tool or apparatus, to be employed in a particular situation, relating to other entities in a grammatically correct way.
When I say that you created an instance of the buttons and labels in your nib file, what I’m really saying is that, when you run your code, a specific portion of your computer’s memory, known by its address, will take care of things in order to generate the user experience you’ve designed. Each time your application is launched on an iPhone or iPad, the interface is recreated by the orchestrated commands residing in your nib files. Consider the nib file associated with the action depicted in Figures 3-14 through 3-16. You dragged a button from the Library into the View window, thus creating an instance of this button. If somebody were to ask you what that means, you might look them in the eye, with a piercing and enigmatic look, and say: “By creating an instance of this button, I have instructed the computer to set aside memory in the appropriate xib file, which, upon the launching of my app, will appear and interact with the user, precisely as I have intended.”
Wow!
Methods
The next concept I would like to explore a little more deeply is that of methods. As with nibs, I’m only going to give you a high-level look this time. You’ve already used methods pretty extensively, so I’m simply going to tell you what you did.
Looking at Figure 3-15, after you dragged the button into your header file, you changed it from an outlet to an action and clicked the Connect button. Then you saw some code appear:
- (IBAction)button:(id)sender
I suggested that to make things clearer, you could have named the method monkey, making it become the following:
- (IBAction)monkey:(id)sender;
Here, you’re instructing the computer to associate an action with a button:
What these two statements have in common, though, is the method monkey. Furthermore, just by the name of IBAction alone, you can see that this is an action that will be performed in Interface Builder. Yup, that’s what that IB in front of Action means. See how Steve Jobs was really saying to himself, when he designed Objective-C on his NeXT computers, that he wanted Actions—and called them IBActions to remind himself and others who used his code that when we typed IBAction it was for Actions used in Interface Builder.
Consider this analogy: a programmer says, “Here comes an app that will help you draw a nice, pretty house.” That’s a header type of announcement. Then the programmer enters specific instructions for how the house will be constructed, how it will sit on/against the landscape, what kind of weather is in the background, and so on. “Draw a slightly curving horizon line one third from the bottom of the display, and midway on this, place a rectangle that’s 4 × 7, on top of which is a trapezoid with a base length of…” and so on. These specific, how-to instructions belong in the implementation file, for they describe the actual actions—the method—of drawing the house. So, for example, if you wanted to connect a button to a method named hello, you’d add this code to the following:
- (IBAction)hello:(id)sender;
This creates a place in memory to execute the code inside your hello method.
Look at the following code, not in terms of methods but in terms of it being a header file and how it relates to its implementation file. Go back to after you created the variable ruaGeek of type Boolean in your header file, as shown in Figure 3-19. Look at the following and calmly absorb the two lines under your ruaGeek of type Boolean—look and absorb as much as you can:
Note When naming things in code, you represent user interface by the initials UI. You represent Interface Builder by the initials IB.
There are two things to note here: first, the @ symbol talks to the innermost part of Xcode, which transforms your code into actions, and second, that the @ symbol has something essential and important to announce. In fact, we call any statement beginning with @ a directive. This @interface directive tells Xcode that you have interface stuff concerning helloWorld_03, and that the particulars will be enclosed within brackets {}. Now take a look at Figure 3-35. The ViewController and the UIViewController interact with the buttons and labels we created. Just gleem over this for now; it’ll all make perfect sense by the time you complete this book.
Figure 3-35. UILabel and UIButton in relation to the UIViewController and the ViewController
The Inspector Bar
You’ve been playing around with the Inspector Bar, so here’s some insight into how the Inspector Bar is set up. Figure 3-36 shows how I illustrate the Inspector Bar on the marker board in class.
Figure 3-36. Focusing on the Inspector Bar
As you become familiar with the Xcode environment, you’ll find yourself using the Inspector Bar to choose a workspace you will need at any phase of your coding. For now, let’s zoom in on the most intense view: the Utilities View. Clicking Utilities View, as shown in the top right of Figure 3-36, you’ll see how I’ve created a zoomed up version of the Inspector Bar, with its submenus located to the left of the panel. Starting at the top, the Inspector Bar contains the following:
You’re still here! Awesome! Take a break for at least six hours and don’t sweat over not “getting” all the code you’ve been digging around in here. Hope you Zenned and zoned out beautifully. See you in Chapter 4.