Chapter    3

Keep on Truckin’

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 image+Tab and then image+Q to close everything until only the Finder is left on your screen.

  1. As you did in the first example, launch Xcode and open a new project with your keyboard shortcut: image. Your screen should show the New Project with Single View Application template, as shown in Figure 3-1. You may find that your Single View Application template was highlighted by default because of the last example. If not, click the Single View Application icon and then click Next button.

    9781430246176_Fig03-01.jpg

    Figure 3-1.  Open Xcode, select the Single View Application template, and click Next

  2. You’re going to call this third project helloWorld_03, so type that in the Product Name box, as shown in Figure 3-2. The Organization Name and Company Identifier should automatically be defaulted to your Xcode license name. Remember that helloWorld_02 was created for an iPad, so the Devices setting on your computer may still be set to iPad. Whatever the case, make sure that the helloWorld_03 Devices setting is set for the iPhone. If Use Storyboards, Use Automatic Referencing Counting, or Include Unit Tests are checked by default, uncheck them. Click Next.

    9781430246176_Fig03-02.jpg

    Figure 3-2.  Name your project, make sure it’s for an iPhone, and then click Next

  3. For this homework assignment, my students are required to take photos of themselves, crop them to 320 × 480 images, and save them as .png files. This way, I can more quickly associate names with the correct faces. If you’re not my student, go ahead and get a picture of yourself, crop it to 320 × 480, and save it onto your desktop as a .png file. (If you don’t have access to a graphics editor, feel free to use the picture I used for this project. You can download it at http://bit.ly/PFXJGe (scroll down to the third video tutorial from the top, helloWorld_03, and click the box icon). A compressed file will be downloaded to your computer with the picture I used in this example, named DrLewis.png.) Place the image on your desktop. Press image+Tab until Xcode is highlighted. When you release the image+Tab keys, Xcode will fill your screen again. Resize Xcode slightly so you can see the desktop with the image, as indicated by arrow 1 in Figure 3-3. Grab it, drag it over to your Supporting Files folder, and drop it there as indicated by arrow 2 in Figure 3-3.

    9781430246176_Fig03-03.jpg

    Figure 3-3.  Drag a picture of yourself from the desktop into your Supporting Files folder

  4. One of the most common mistakes students make happens at this simple stage of Xcode management: They forget to check the “Copy items into destination group’s folder (if needed)” checkbox. When you import a file into the Supporting Files folder on your computer, if you don’t check “Copy items into destination group’s folder,” everything will seem fine, giving you a false sense of security. In this case, even though Xcode is told that your supporting files, such as the image in this example, reside in your Supporting Files folder, what’s really happening is that there’s a little note saying: “Dude, I take no responsibility for this, but the file is not here, it’s still on the owner’s desktop!” So you, the writer of your code, go on doing your homework. Every time you run your code, and Xcode calls to access a supporting file, this irresponsible “pointer reference” guy just keeps saying, “It’s not here—it’s still on your desktop!” So you finish your homework and everything works great. You smile as you zip up your work and send it to me. I give you a zero and then you cry. Why? Well, the irresponsible pointer reference is telling me that your reference files are on my desktop. Nope! They’re not on my desktop, they’re on yours, and you get zero for being negligent and depending on a pointer reference dude rather than selecting the “Copy items” check box. So, after dragging your picture into the Supporting Files folder, check the “Copy items into destination group’s folder (if needed)” check box, as shown in Figure 3-4, and then click Finish. Now you’re in good standing, and won’t be brought to tears by the pointer reference dude.

    9781430246176_Fig03-04.jpg

    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.”

Creating the User Interface

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.

  • 5.  Open your nib file, as you did in the two previous apps. Open your helloWorld_03 folder and select the ViewController.xib file, as illustrated in Figure 3-5.

    9781430246176_Fig03-05.jpg

    Figure 3-5.  Open your nib file

  • 6.  Click the Object Library icon and make sure you’re in Icon View (the icon with four little squares, above the Text icon in Figure 3-6, is highlighted). You’ll be dragging screenviews, labels, and buttons onto the View Design area.

    9781430246176_Fig03-06.jpg

    Figure 3-6.  Open the Object Library

  • 7.  With your Utilities pane open, as shown in Figure 3-7, from the bottom section of the panel, drag an Image View (most often referred to by its full name, UIImageView, by coders and at Apple demonstrations) onto your View Design area. You need a UIImageView because you need to have an image of you underneath the buttons and text labels. That picture that you just dragged in needs to have a place to live, and a UIImageView is just the thing for this job. It’s going to reside underneath all your buttons and embrace whatever picture you tell it to embrace.

    9781430246176_Fig03-07.jpg

    Figure 3-7.  Drag a UIImageView onto your View Design area

  • 8.  Remember the image you dropped into the Resources folder back in Figure 3-3? That’s the image you will want the UIImageView to be, so drag it onto your View Design area to encapsulate it. Make sure you’ve selected the Attributes Inspector in the Inspector Bar. With the Attributes Inspector open, click the Image drop-down menu, and guess what you’ll see. You’ll see the name of the file you dragged into the Resources folder. Select it, and voila! The image appears in your View Design area. Isn’t that cool?

    9781430246176_Fig03-08.jpg

    Figure 3-8.  Associate your selected image with your UIImageView

  • 9.  Drag a label from your Library onto your View Design area and place it at the bottom, as shown in Figure 3-9. Make sure it’s nicely centered as indicated by the blue line. Just to remind you: when you click a button you’ve yet to drag onto the View Design area, your code will invoke an action that will change the text in this label field object (depending on whether the code thinks the user elevated himself to the rank of geek or not).

    9781430246176_Fig03-09.jpg

    Figure 3-9.  Drag a label onto your View Design area

  • 10.  After releasing your label, with it still selected, in the Attributes Inspector and as illustrated in the three images in Figure 3-10, you’ll do three things:

    9781430246176_Fig03-10.jpg

    Figure 3-10.  Center, change color, and delete the label text

  • a.  Center the text (left image).
  • b.  If the text is over a dark area, change the text color to white (center image).
  • c.  As weird as this sounds, delete the text inside it because you’ll be generating your own, changing text, through code with an if-else statement (right image).
  • 11.  Drag in a button and place it, centered horizontally, toward the upper portion of your View Design area, as shown in Figure 3-11.

    9781430246176_Fig03-11.jpg

    Figure 3-11.  Drag in a button and center it toward the upper portion of your View Design area

  • 12.  You need to ask the user: “Are you a Geek?” Double-click the button and enter the text, as shown in Figure 3-12. Don’t worry about resizing the button to accommodate the text—Xcode automatically figured that out for you.

    9781430246176_Fig03-12.jpg

    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.

  • 13.  You need to make more space and adopt the habits of seasoned coders. Close the Utilities Inspector (arrow 1 in Figure 3-13) and select the Assistant Editor (arrow 2), which looks like the chest of a person wearing a tuxedo. See how the layout changes. Just for fun, you may want to temporarily click the button immediately to the left of the Assistant Editor, called the Standard Editor, and you’ll see that now you have one screen. Make sure the Assistant Editor selected before moving on.

    9781430246176_Fig03-13.jpg

    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+image+Return) and the Standard Editor (image+Return). There are thousands of keyboard shortcuts; some achieve superstardom, and some never make it out of books and blogs.

  • 14.  As you can see, you’re back at a familiar screen that shows Interface Builder with your header file centered in the middle. Here you want to associate outlets and actions with the buttons and labels you dragged to the View Design area. The last two times you did this, you were told to drag from this to that. Now you’re going to use a bit more of the correct nomenclature so you can sound geekier. Click once inside the button and then Control-drag from the button to your header file, placing it under the @interface directive. If you were to Control-drag to an invalid destination, Xcode wouldn’t display the insertion indicator, shown in Figure 3-14. Note that as you drag over to this area, Xcode already knows that this could be one of three options, not two, as shown in the insertion indicator for label and text box outlets.

    9781430246176_Fig03-14.jpg

    Figure 3-14.  Control-Drag a connection from your button in Interface Builder directly into your header file

  • 15.  Change the Connection type in the top drop-down menu in the dialog box from Outlet to Action, as shown in Figure 3-15.

    9781430246176_Fig03-15.jpg

    Figure 3-15.  When the button’s connection dialog appears, specify what type of connection you plan to use in your code

  • 16.  Click once inside the Name field and call your button button, as shown in Figure 3-16.

    9781430246176_Fig03-16.jpg

    Figure 3-16.  Name your button button

  • 17.  Control-drag from the label to your header file, placing it under the Button’s IBAction line of code, as shown in Figure 3-17.

    9781430246176_Fig03-17.jpg

    Figure 3-17.  Control-drag from the label into your header file

  • 18.  You want to keep the label as an outlet, so leave the Connection type alone. You do want to give it a name, though. Name it label for now (see Figure 3-18).

    9781430246176_Fig03-18.jpg

    Figure 3-18.  When the label’s connection dialog appears, specify what type of connection to use in your code and name it label

  • 19.  Figure 3-19 shows the header file coded without your typing a single letter. Before moving on, make sure your code looks like that shown in Figure 3-9 and as follows:

    9781430246176_Fig03-19.jpg

    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.

  • monkey’s return type: Your monkey method returns stuff, which is explained by saying: “Method monkey’s return type is an IBAction.” Read the bold code louder:
    - (IBAction) monkey:(id)sender;
  • monkey’s argument: Your monkey’s argument is of type ( id), which in your case, points through the sender to the button you dragged into the header file in Figure 3-14. Read the bold code louder:
    - (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.

  • 20.  Get your screen in a condition conducive for writing code by closing the Assistant Editor you opened (see arrow in 2 Figure 3-13) and then opening the Standard Editor, as shown in Figure 3-20.

    9781430246176_Fig03-20.jpg

    Figure 3-20.  Close the Assistant Editor and open the Standard Editor

  • 21.  I hope you’re already in the habit of saving things. Go over to your nib, header, and implementation files that are now colored dark grey, as shown in Figure 3-21. (Note that my ViewController.h is not greyed because I am in the process of saving it.) Click each one and save them by pressing image+S. Or use image+Option+S to save all. Please don’t use your mouse to save, as I will magically appear, take your book away, and declare that you have failed in your endeavor to become a geek.

    9781430246176_Fig03-21.jpg

    Figure 3-21.  Save everything

  • 22.  You have one more thing to do before you can code. Open ViewController.h, as shown in Figure 3-22.

    9781430246176_Fig03-22.jpg

    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.

  • 23.  Your app is going have a user tap the button asking whether they are a geek or not, and the label text will alternate between two messages. Regardless of what the content of these messages is, it needs to switch between one message and the other. In other words, you need to make one situation false and the other positive. That means you have to create something called a variable that can switch between states of positiveness and falseness, also known as Boolean. Let’s name your variable ruaGeek. To program it, you have to first declare it in your header file as being of type Boolean. Make a space under the #import line and type bool ruaGeek, as shown in Figure 3-23 and the following code. Now, when you go to the implementation file and program what you want it to do, you can have it be in a false or positive state.

    9781430246176_Fig03-23.jpg

    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
  • 24.  You need to tell the button’s action what to do. You know you’ll use a variable called ruaGeek to be in a state of positiveness or falseness, and you also know that the code you’ll write will be for (IBAction), so let’s do it. Open the implementation file and do what we love to do: code!

    9781430246176_Fig03-24.jpg

    Figure 3-24.  Open the implementation file

  • 25.  Scroll down to the button method you created when you dragged in and created the button in Figures 3-14 through to 3-16. For now, ignore the @directives at the top of the page and the ViewDidLoad and didReceiveMemoryWarning methods the clever people at Apple instantiated for you. Focus on the button method. Remember my saying that you could have named this method monkey—the one that tells the code what to do when the button is tapped? Inside the squiggly brackets, you’re going to tell the iPhone exactly what to do when the button is tapped. If it’s the first time the button is tapped, it will say one thing, and if it’s the next time the button is tapped, it will say another thing. Then repeat. To decide whether it’s the first time, you’ll use an if-else statement, which is something used every day in coding. So let’s drag a snippet of if-else code from the library.

    9781430246176_Fig03-25.jpg

    Figure 3-25.  Make some space between the button’s squiggly brackets

  • 26.  To find the if-else snippet of code you need, you’ll have to open a section of the Library that you’ve not gone to before. As shown in Figure 3-26, open the Code Snippet Library by clicking its icon.

    9781430246176_Fig03-26.jpg

    Figure 3-26.  Open the Code Snippet Library

  • 27.  Scroll down until you reach the If-Else Statement snippet, shown in Figure 3-27.

    9781430246176_Fig03-27.jpg

    Figure 3-27.  Select the If-Else Statement snippet

  • 28.  Drag the snippet of code onto the canvas and drop it between the two squiggly brackets of the button method, as shown in Figure 3-28.

    9781430246176_Fig03-28.jpg

    Figure 3-28.  Drag the snippet into place

  • 29.  Look at the if-else statement. What it’s saying is that if something is true, do “this”—else do “that.” Here’s how to go from English to pseudo code:

    Top level:

    if ( First Condition ){Do this } else {Do that )

    Next level down, a little deeper now:
    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.

    9781430246176_Fig03-29.jpg

    Figure 3-29.  Make some space between the button’s squiggly brackets

    9781430246176_Fig03-30.jpg

    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 #>
    }
    }
  • 31.  The first message is “Shut up! You’re not!” (For those not in a university or high school setting, this is not an insult—it’s a joyous affirmation. For example, a student says to her friend, “I got an A for the exam.” Her friend affirms the joy of receiving the A and says, “Shut up! You did not get an A!”) So your first statement, when ruaGeek is true, has to say “Shut up! You’re not!” to the user. Then you need to change the value to false so you can invoke statements-if-false later. Type the following code:
    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.

  • 31.  Change label.text=@"Shut up! You're not!"; to label.text=@"You are";. Then you need to change the value from ruaGeek=false to ruaGeek=true so you can invoke the next statement, as shown in Figure 3-31.

    9781430246176_Fig03-31.jpg

    Figure 3-31.  Set the initial condition to true

  • 32.  Now run it, as shown in Figure 3-32. Uh-oh, there are two things you need to correct!

    9781430246176_Fig03-32.jpg

    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.

  • 33.  Looking at the image on my screen (not your screen, you probably placed the image perfectly), there is a grey gap between the bottom of my image and the iPhone body. Let’s fix that. Also, let’s say your client first wants to see “Shut up! You’re not” when the user clicks on the phone button! No problem. Just adjust the UIImageView down until it fits perfectly. Then leave the xib file and open your implementation again; it seems to be running the statements in the else section (that is, the value of ruaGeek is false) to begin, so you can either change all the values of ruaGeek to their opposite or simply swap out what you say. Figure 3-33 and the following code do the latter:

    9781430246176_Fig03-33.jpg

    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;
    }
  • 34.  Run it and click, as shown in Figure 3-34! Yeah!

    9781430246176_Fig03-34.jpg

    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:

  • I have received hundreds of emails from readers from the first and second editions of this book saying that knowing it was okay to blank out and not feel pressured to understand the code really worked out for them.
  • My students love it when, at the end of each class, I make them turn off their Macs, put down their pens, Zen and zone out, and just casually listen to me. I’ve had students knocking on my office telling me in many colorful ways how the Zenning and zoning really worked for them.

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:

  • Nibs, zibs, and xibs: Instances and Instantiation
  • Methods: Instance methods and class methods
  • Header files
  • The Inspector Bar
  • Memory management

Nibs, Zibs, and Xibs

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.

  • Instances: All the information that resides in these files is put there so that it can create an instance of the buttons, the labels, the pictures, and so forth that you’ve entered. This collection of commands is plonked down and saved into your nib files to become the UI. The code and the commands taken together become real, and they’re sensed by the user—seen or heard, or even felt.
  • Instantiation: Remember in step 25 and Figure 3-25, I explained that you can see that you have the method - (IBAction)button:(id)sender{. . .}? Well, the term instantiate can be usefully explained if you consider what happens when you first save a new project. The computer instantiates—makes real and shows you the evidence for—a project entity created by assigning it a body of subfiles. In helloWorld_03, you saw how in Figure 3-21 I asked you to go over to your nib, header, and implementation files that were colored dark grey and save them? Well, excuse me, how did these files get here? Did you program them or make them? Nope, Xcode instantiated them when you created your project. Xcode gave your project “arms and legs”: two AppDelegate files and two ViewController files. The same happens when your app instantiates buttons and other objects as part of its operation; the app does it for you.

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:

  • The first symbol in this piece of code is a minus sign (). It means that monkey is something we call an instance method.
  • On the other hand, if you had entered a plus sign (+) there instead, as in + (IBAction), it would be called a class method.

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.

Header Files

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.

9781430246176_Fig03-35.jpg

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.

9781430246176_Fig03-36.jpg

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:

  • File inspector: This is where you manage file attributes such as name, type, and path within your project.
  • Quick Help: Just what it says.
  • Identity inspector: Gives access to deep stuff such as class names, access, and labels.
  • Attributes inspector: For adjusting attributes available to an object.
  • Size inspector: Allows you to tinker with an interface object’s initial size, position, and autosizing.
  • Connections inspector: Allows you to view the outlets and actions for your interface objects.
  • Bindings inspector: For configuring bindings for view objects.
  • Effects inspector: To adjust animation protocol such as transitions, fades, and other visual characteristics of selected objects.
  • File templates: Common templates that you can drag from the library to the project navigator.
  • Code snippets: Like clip art but for coders—snippets of source code that you can use by dragging into your files.
  • Objects: You use these interface objects by directly dragging onto your nib file in the Interface Builder editor window.
  • Media files: Just as it says, they are graphics, icons, and sound files that can be dragged directly to your nib file in the Interface Builder editor window.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset