Switches
After finishing the touches app in Chapter 5, you can say without flinching that you’ve coded Objective-C apps! You’re not alone if, while coding Chapter 5, you felt as though you were struggling to make your way across a tough and rocky road. I say this because all programmers have had to journey over this road. It’s absolutely okay to look back on that chapter and not remember what you did. That’s normal, and I’m about to prove to you that it’s normal. First, I need to explain why you’re going to take time out at this point.
In my experience, when teaching students languages such as C, C++, C#, assembly, machine languages, Java, and others, many students drop out even when they seem to be doing fine. In recent years, I began to catch students as they neared this junction, and I would ask them why they were contemplating dropping out. They would all tell me something similar to this: “I can see I did the homework but I’m scared I will fail because it’s just not sinking in. I don’t grasp it.” About four years ago I tried an experiment. When the students walked into the lecture hall they were in shock when I told them to close their textbooks, close their laptops, and put away their books because we were going to take a journey inside their brain and have a class on neurology. In fact, we were going to scientifically illustrate why many felt they were stupid, not getting it, and essentially feeling like a dork. The entire lecture hall collapsed in laughter. At the end of the lecture that I now call “Don’t Freak Out! Let’s Have a Look at Your Brain!” some students were crying and came up to me after class and thanked me. Not a single student dropped out.
Right now, I bet that you feel that you’ve not retained anything from Chapter 5 and that you feel a little overwhelmed and insecure in your geek abilities. Well, that’s okay—just read on and you’ll see why you feel a little uneasy. Even if you do feel confident at this point, you’ll probably falter at some point down the road as it gets harder, but I still want you to read on. This is important, so I want you to really understand this.
Don’t Freak Out: Let’s Look at Your Brain!
One of the best ways to explain this is to ask you something that has nothing to do with Objective-C and computer science. It’s about childhood memories.
Do you ever smell something you’ve not smelled before and without any warning your brain immediately takes you back to a place in your early childhood? This happens to all of us. After smelling this smell, you’ll suddenly see everything clearly in your head: the walls, the people—it’s all crystal clear. And sometimes it may overwhelm you emotionally. You may feel blown away that you’ve not thought about those walls or images for many years, and now suddenly they’re overwhelming your senses. Let me explain why this happens. I will use my smell of old-fashioned soap to illustrate this, and then show how this is related to the neural connectors you’ve just created.
Look at Figure 6-1. Under the first title, ILLUSTRATION, you see a very simplified illustration of how, once your brain receives a new input that it’s never experienced before, it creates a nucleus housed inside a cell body that retains that event. This is connected to the rest of your brain by threads and axons. As you experience new events that relate to this new event, a tree of synapses and neurons connect to this nucleus. Some of these connections become quite full of what are called dendrites.
When I was a little boy in Durban, South Africa, I went down to where the servants were washing laundry. Back in 1963, most families used old-fashioned ammonia-filled soap that had a very distinct smell. This smell created a new nucleus in my baby brain. It connected with the joyful songs the Zulu servants were singing as they hand-washed the laundry. My brain also connected the imagery of the walls, the paint, and my dog Samson. These connectors of the singing, the walls, the paint and the dog formed four groups of connections to that new smell, as illustrated under SYNTHESIZED in Figure 6-1. Some groups immediately had more connections, such as songs, because I used to sing many Zulu songs as a small boy. The next biggest group was probably that of my dog. I’ve labeled the groups from 1 to 4 in order of size.
Many years later, in New York City, probably around 1993, I was rushing to keep an appointment with a law professor who had said he would meet me for lunch at a little restaurant. As I was running across 8th Avenue, I noticed some people cleaning the sidewalk in front of another restaurant. They were using soap and water and scrubbing it with these large straw brushes. Suddenly I smelled it. The smell I hadn’t smelled since I was three in that laundry room. I suddenly saw those servants, I could hear their songs and laughter, and I could see my old dog Samson. I became so overwhelmed with that day, the people, and the energy from so long ago that I stopped running and started crying. When I reached the restaurant, the law professor stood resplendent in his tweed suit and said, “Rory, it’s okay that you’re a couple of minutes late. Oh, my gosh, are you crying?”
Figure 6-1. Don’t freak out: Let’s have a look at your brain
So what happened? What happens when you experience similar events? Why does this often happen with smell? Let’s first look at events in life, such as the first time you realized that 1 + 1 = 2. Do you remember the first time you realized 1 + 1 = 2? Probably not. That’s because after you created a nucleus associating 1 + 1 = 2, trillions of connectors were going to 1 + 1 = 2. Every time you perform any function that relates to 1 + 1 = 2, your brain makes a connection to the nucleus housing 1 + 1 = 2. Even as you flip through this book and it goes from page n to n + 1, you make synaptic connectors to dendrites and groups of associations connected to 1 + 1. Somewhere in those trillions of 1 + 1 = 2 connectors are the visuals and sound effects of the room where you realized this, but it is lost in the maze of trillions of other connectors.
That rare smell though, that’s different. Think about it. I have illustrated four groups associated with that smell from when I was three. Over the next 30 years, following the creation of that nucleus and the four groups linking it, there was never a connection made. It just lay there. However, as I crossed 8th Avenue and smelled that smell, it immediately invoked that same nucleus and the contents of the four groups connected to that event. These connectors were strong because they were not interconnected with other complex relationships. This made the singing, the feeling I had towards my dog, the laughter, and the other events come hurtling into me.
Now go back to when you read Chapter 5 for a moment. Look at the YOU RIGHT NOW illustration in Figure 6-1. You created a set of nuclei when you made your way through Chapter 5. Let’s imagine, for the purposes of illustration, that it was only one event or one thing you learned while reading Chapter 5. The nucleus containing that knowledge is housed in the light grey circle. You may, at the most, have created one semblance of connectivity to some related thought or concept. That’s why I connected one small group to the Chapter 5 knowledge nucleus. More importantly, notice that I’ve created five other groups of potential connectors to Chapter 5: they are “Rest of the book,” “Problem solving,” “Teaching to others,” “Real life application,” and “Making $$.” Right now it’s absolutely natural that these groups have no connectivity to the nucleus of Chapter 5’s knowledge because you have not had time to create these connections. For example, right now, as you read this chapter, you probably “feel” like you have no connection to the knowledge you gained in Chapter 5. That’s because there is no connection to it as you read this. There is also zero connectivity to making $$ from what you learned in Chapter 5, nor to the other groups.
I carefully choose topics, innuendo, and semantics to optimize, as best I can, connectivity between what I teach at the moment to what was taught in the past. By the time you reach the end of this book, create your first app, and sell it, your brain will have begun to create many connectors to Chapter 5. I’ve illustrated this in Figure 6-1 under GEEKDOM. Something that connects a huge amount of synapses to nuclei containing a difficult-to-understand concept is teaching others. It’s great to go onto forums, such as mine at www.rorylewis.com/ipad_forum/, and help out newbies with their questions (even if you’re a newbie yourself) because it creates many connections to that difficult concept, making you smarter. In essence, helping others forces one to answer the same question in thousands of different ways. So, I strongly encourage you to go to the forum, ask questions, and then, as you become wiser, help others.
So, the first good news is that it’s okay to feel disconnected to what you coded in Chapter 5. You’ll make those connections as you move forward. The second piece of good news is that Chapter 6 will not be as huge a leap as Chapter 5 was. Instead, you’re going to take a break from serious code and connect new ideas to the synapses that you connected with code in Chapter 5. In fact, in both Chapters 6 and 7, there will be very little code! Instead, I will connect cool new thoughts to the portion of your brain that’s associating code with ideas explored in Chapter 5. Once you’ve established these connections in your brain, you’ll associate more code. In Chapter 6, you’ll explore a popular method for navigating through iPhone apps using the platform of a Tabbed Application. But for now, just relax and enjoy the chapter.
switches: A Tabbed Application
So far, you’ve written code that allows the user to poke or prod an iPhone or iPad in certain ways to make it do interesting things. That’s now going to change. In this chapter, you’ll demonstrate how to create an iPhone app that allows you to do all of these cool functions without overwhelming your user, by dividing the functionality into several easy-to-locate tabs. This model, called the tabbed model, is so popular among app developers that Apple has included a basic Tabbed Application project in the New Project options in Xcode. In other words, the people at Apple recognize how much programmers like to use this model, so they created most of the code you need. When you’re all done writing this app, you’ll have a display with two tabs at the bottom. The content of the first tab will be an image that you set using Interface Builder with a button overlaid on top of it. This button will cause Mobile Safari to open the Apress web site. The content of the second tab will be a different image, but you can set the image name and other attributes in the implementation file.
You can watch a video of this switches app at http://bit.ly/SFmG64 and simply follow along with me. You can also download the code to this project at http://bit.ly/SzvMif where you can visually compare your code with mine. Most importantly, you’ll need to download the 16 images and DemoMonkey file from http://bit.ly/SFn70d.
Figure 6-2. Download the three images onto your squeaky clean desktop
Now, let’s create the app.
Figure 6-3. Start a Tabbed Application
Figure 6-4. Name the app switches
Note I have not selected Automatic Reference Counting in this project because there will be no need to use large memory management here. Automatic Reference Counting makes Xcode manage memory on the compiler and manage retain, release, and autorelease.
Adding the Images to the Project
At this stage, it’s probably a good idea to drag your imagery to use on the tabs, so you won’t have to worry about it later.
Figure 6-5. Drag in your three images from the desktop
Figure 6-6. Copy the items into the destination page’s folder
Figure 6-7. Drag your icons to the app’s icon property
Figure 6-8. Housekeeping: move icon apps to Supporting Files folder
Some of the readers of previous editions of this book and students from my former classes actually work at Apple, developing iOS code and doing the very special things you’re about to see in this in step 9. That’s why I love to say, “The clever people at Apple have coded…” because these clever people at Apple include people just like you, who began right here, reading the first version of this book. Right now, you probably just want to see what the clever people have coded for the Tabbed Application.
Figure 6-9. Run it so you can see what Apple has already coded for you
Figure 6-10. The first view to pop up will be the . . . First View
That Second View that you see in Figure 6-11 can be replaced, along with the introductory First View, with code, or the next level of a game, or the details of an address tab or recipe. For your purposes, simply insert a first image into the First View and a second image into the Second View.
Figure 6-11. The Second View appears when you select the Second tab
Figure 6-12. Open up the First View nib file
Figure 6-13. Drag a UIImagView onto your view
Figure 6-14. Associate your first images with the first UIImageView
Figure 6-15. Open up the Second View nib file
Figure 6-16. Drag a UIImagView onto your view
Figure 6-17. Associate your second images with the second UIImageView
Okay, you’ve successfully populated the background of both views with some cool wallpaper. In essence, you’ve customized the two views to look pretty cool and pretty custom. Now you’ll move on to customizing your buttons. Up until now, you’ve used the default buttons, and you may have thought to yourself how come all the cool apps I see have buttons that look so different and so innovative? Well, just as you customized the views, you’re going to learn how to customize your buttons. You’ll have a custom button going to the Apress web site on the First View, and then eight custom buttons in the Second View going to various social media sites.
Figure 6-18. Drag a button onto the First View
Figure 6-19. Change the Apress button to a Custom type
Figure 6-20. Delete the default text from the Apress button
Figure 6-21. Associate the Apress image with the Apress custom button
Figure 6-22. Adjust the size of the button
Figure 6-23. Run it: you have two views and a custom button already!
Figure 6-24. Add the first button to your Second View
Looking back at what you’ve done and where you want to go: you’ve created the Apress button on the First View. You now want to create eight buttons on the Second View that link to various social media sites.
Figure 6-25. Create the first custom button for the Second View
Figure 6-26. Copy the first button
Figure 6-27. Paste the copied button alongside first one
Figure 6-28. Select and copy the first two buttons and paste them
Figure 6-29. Paste the four buttons you copied
Figure 6-30. Name the remaining icons
Table 6-1. The Eight Icons
Connecting and Coding the Buttons
You now need to code the lone Apress button on the First View and then the eight social media buttons you’ve just created in your Second View. Because you’re here on the Second View with your social media buttons, let’s first connect these to the Second View’s header file. Once that’s done, you’ll then go back to the First View and connect your Apress button to the header file.
Once all y our buttons are connected, you’ll code the First View’s implementation file’s NSURL by hand, so you can learn it the old-fashioned way. Last, you’ll bring in the eight NSURL instances for the Second View all in one swoop via DemoMonkey to save time and tediousness. I do things this way because there’s always a balance between encouraging students to type code the old-fashioned way, doing it by hand, so that the synapses make appropriate connections, and not making them do tedious work that in the real world would be done differently using tools. If you just use tools to bring in code, you never get to learn how to code yourself or what the small nuances of each line of code really mean. On the other hand, if I only make you type in all that code by hand, then you miss out on having hands-on experience using tools used in the workforce, such as DemoMonkey.
Having you code the Apress URL in the First View by hand and then learning DemoMonkey gives you the best of both worlds.
Figure 6-31. Get your canvas ready for coding
Figure 6-32. Re-inspecting the code
Figure 6-33. Make the connection an Action
Figure 6-34. Connecting the Facebook button
Table 6-2 Renaming the Buttons
Figure 6-35. Connecting the last of the social media buttons
Figure 6-36. Before you continue, check that your page is like mine
Figure 6-37. Back to the First View
Figure 6-38. Change from an alternate to an action
Figure 6-39. Name it apress
Figure 6-40. Make sure your code is like mine
Figure 6-41. Set the stage for coding
Figure 6-42. Start with the First View
Figure 6-43. Go to the apress method
Figure 6-44. Create two sets of square brackets
Figure 6-45. Type UIApplication
Figure 6-46. Enter sha
Figure 6-47. Step out of the first set of squiggly brackets
Figure 6-48. Delete the NSURL pointer
Figure 6-49. Enter [NS for a bracketed NSURL
Figure 6-50. Bring in the URL with string
Figure 6-51. Delete the string section
Figure 6-52. Enter the Apress URL
Figure 6-53. Run it and click the Apress button
Figure 6-54. Open the SecondViewController.m file
Figure 6-55. Delete the instantiated empty methods
Figure 6-56. Dragging in our DemoMonkey file
Figure 6-57. The code inside DemoMonkey revealed
Figure 6-58. Your sixth iPhone app
Figure 6-59. Some of the social media sites
Figure 6-60. Four more views
In this chapter, you spent some time digging the code already. One issue you may want to look at is compiling, how the computer looks at your code and implements what you wrote. Sometimes students get mixed up between compile-time and runtime. If you feel fresh and want to read this, go ahead. Otherwise, I’ll see you in Chapter 7. Good job!
Compile-time indicates that something happens when your project is compiled, or built, prior to being run on the Simulator or on a real iOS device. These are things like the definition of classes in .h and .m files, the organization and layout of UIView instances in your nib files, and the configuration you do in Xcode’s various inspectors. Everything that is set at compile-time defines exactly the state your app will be in when it’s started.
Runtime, on the other hand, describes the segment of time after your app has started running. This is when all the code you’ve written is actually executed, effecting changes in the state of the app from the way it was set up at compile-time. In this chapter, you specified the image for the second tab through a message in your implementation file. Thus, the image to show was unspecified at compile-time, but at runtime a series of instructions was executed to display the desired image in the UIImageView you provided. In essence, both load at compile time but while the code behind the second image is not executed by the user, it will remain compiled but unspecified. The instant the user executes the code for the unspecified image, the runtime associates the image to the secondViewController and the image is now specified.
Why is this difference significant? You proved, during the course of writing this app, that you can do the exact same thing at runtime as you could at compile-time. However, executing instructions to do what you wanted required several extra clicks and drags and a few more lines of code. If you already know how you’re going to configure something at compile-time, the advantages of writing code to do the same thing will diminish. However, if you want to dynamically change the properties of an object during the execution of the app (last chapter’s touches app is a great example of this), it’s obviously impossible to set all aspects of the state at compile-time.
In short, compile-time defines the starting state of your app, whereas runtime describes the actions that occur once your app begins running.
In Chapter 7, you’ll move into the next level of complexity: storyboarding. Storyboarding is the new way Apple lets you lay out how a user moves through an app, in much the same way that a movie producer sets up a storyboard to show how a movie will go from one scene to the next. Storyboarding has segues (pronounced “segways”) that connect each view in your app with another. It is tempting to just go straight to storyboarding, but it’s best to first learn a little about the code behind these buttons and images, as you have done. So take a break, and then let’s move on to the land of storyboarding.