﻿ ﻿Introduction to Programming - Introducing iOS 8 (2015)

# Introducing iOS 8 (2015)

### Chapter 2. Introduction to Programming

Programming can be a daunting concept, but it doesn’t have to be. Most programming boils down to some basic math skills. No matter what level of math you have taken in the past, you will now learn the basics to get started. Before you start developing apps, it’s important to understand how the magic happens behind the scenes. In this chapter, you will learn the basics of programming, how virtual objects are created, and some best practices to keep your code neat and clean. After you learn these concepts, you will put your knowledge to work and build your first app.

Learning to program is like learning to ride a bike. At first, the concept seems impossible, and you have no idea how to do it. It’s not that you don’t have the basic skills to ride the bike; it’s that you haven’t used those skills together before now. Programming is teaching your brain to think differently; the basic skills are not different, it’s just a new concept.

Building Blocks

We are going to start to define the basic building blocks of a programming language. These are new concepts, and it is normal to do a double-take while learning them. They might sound foreign at first, but so did riding a bike.

Variables

When you check your bank account balance, it shows the current amount of money you have available. Your bank account may be \$100 at the beginning of the month, and \$350 on your payday. Since the amount of money in the account varies, the term “account balance” is used to represent the current amount. This is an example of a variable. A variable is a representation of a value. Variables come in many different shapes and sizes. Different types of variables hold different types of values. Variables can hold numbers, letters, words, true, false, or even a custom car.

Integer

An integer is a whole number, a number without any decimal places, positive or negative:

-10, 0, 100, 21031

An integer could be used for the number of stars for a movie review, a house’s street address, or the score for a sports team.

Float

Sometimes, you need to be more precise with a value. In the case of currency, a decimal place is used to keep track of the cents on a dollar:

\$10.51

A decimal-based variable is called a float. Float is short for floating point, another name for a decimal place.

Boolean

If someone asks you if the sky is blue, you would respond with either Yes or No. You cannot respond with 7, \$103.45, or “Banana.” This kind of Yes or No variable is referred to as a Boolean. Boolean variables are similar to a light switch—they are either on or off, true or false; there is no in-between value.

String

When someone asks your name, you respond back with a collection of letters that form a set of words:

"Steve Derico"

A string is used to represent characters strung together to make words and sentences. A string can hold a series of letters, numbers, and symbols. Strings are surrounded by a pair of quotes. For example:

"Steve is cool."

"Where is the ball?"

"Go Giants"

Classes

When you look at a busy road, you see many different types of automobiles. You see SUVs, sports cars, trucks, and sedans. Each type of car may look different, but every car has a few core characteristics. Every car has wheels, an engine, and brakes. Every type of car, no matter the brand, model, or style must have these core characteristics. Without these core characteristics, the car would not be a car. These core characteristics are called attributes.

A car is more than just a bunch of pieces of metal; it has a purpose and provides value to the consumer. A car can drive, honk, brake, and steer. These basic methods are available in every car. Without these methods, it would not be a car. These core methods are called behaviors.

If you were designing a new car, a blueprint would be a good place to start. A blueprint is a document that serves as a template for building something. The blueprint defines the attributes and behaviors of the car. A basic blueprint for a car might look something like Table 2-1.

Table 2-1. Car blueprint

 Has Wheels Has Engine Has Brakes Can Drive Forward Can Stop Can Steer Left and Right

The items beginning with has are the attributes. The items beginning with can are the behaviors. You can now use this blueprint to produce many cars in your factory, and each one will have the attributes and behaviors listed in the blueprint.

A class is a blueprint for a virtual object. A class defines the required attributes and behaviors. Just like a cookie cutter, a class can produce endless objects from a single blueprint. A star-shaped cookie cutter can create an unlimited number of star-shaped cookies. Each cookie will have the same shape as the cookie cutter.

Objects

If all cars have the same attributes, what makes a car unique? The values to these attributes make them unique. You might see a green station wagon driving down the road with standard wheels, a diesel engine, and standard brakes (Table 2-2). Then you might see a red sports car driving down the road with big wheels, a big engine, and performance brakes (Table 2-3). These cars each have different values for their attributes.

Table 2-2. Green station wagon

 Wheels Standard Engine Diesel Brakes Standard Acceleration Poor Stopping Great Steering Fair

Table 2-3. Red sports car

 Wheels Big Engine Big Brakes Performance Acceleration Great Stopping Great Steering Great

Each of these cars is an object from the car class. An object is the product produced by a class. An object has the attributes and behaviors from its class, in this case, the car class. The words instance and object are commonly used as synonyms. Keep an eye out for them, because people tend to use them interchangeably.

NOTE

Keep up with the list of synonyms in Appendix B.

You are an instance of the human race. There is no other human identical to you, even if you have a twin. Each person is completely unique. All humans have attributes like eye color, hair color, and a name. For example, see Tables 2-4 and 2-5, where the attributes are listed on the left, and the values are listed on the right.

Table 2-4. Person A

 Eye Color Blue Hair Color Blonde Name Larry

Table 2-5. Person B

 Eye Color Brown Hair Color Brown Name Magic

The combination of the values with their associated attributes is what makes an object unique. Humans have hundreds of attributes and thousands of possible values for each attribute. The permutations are endless, and as a result, each human is different from every other human.

PERSONAL CHALLENGE

What are some other examples of attributes for the human race?

Methods

Every morning when you wake up, you likely follow a simple routine of steps: get out of bed, take a shower, brush your teeth, get dressed, eat breakfast, head out the door. This routine of steps is very similar to how a computer works. A computer processes a list of steps to achieve a task. This list of steps is called a method. A method is a collection of code to complete a specific task. If you wrote a method for your morning routine, it might look like this:

1. Wake up.

2. Get out of bed.

3. Take a shower.

4. Brush your teeth.

5. Get dressed.

6. Eat breakfast.

7. Head out the door.

The method is executed every morning when you wake up. You know by the time the method is complete, you will be ready to take on the day. The completed result from a method is called the output. The input is what goes into the method, like an ingredient for a recipe, or a tree before it is made into paper, or in this case, your sleepy body.

PERSONAL CHALLENGE

Write down all the steps it takes to make a peanut butter and jelly sandwich. See how specific you can be.

Inheritance

Children often share the same facial features as their parents. “She has her father’s eyes.” “She has her mother’s nose.” The genes and traits of the parents are combined when the child is created. The parents’ attributes and behaviors are passed down to the child. A parent and child may have similar attributes like hair color, eye color, or skin color. A parent and child may also have similar behaviors like the ability to play a sport. A father and son duo like Ken Griffey, Jr. and Ken Griffey, Sr. both possess the work ethic and physical traits to be professional baseball players.

The passing down of attributes and behaviors from parent to child is called inheritance. Inheritance is the ability for a class to extend or override functionality from a parent class. Imagine the car class you created (Table 2-6) was the parent of the SUV class (Table 2-7). The SUV class will inherit all the attributes and behaviors of the car class. The SUV will also be able to add its own attributes and behaviors.

Table 2-6. Car

 Wheels Standard Engine Standard Brakes Standard Can Drive Forward Can Stop Can Steer Left and Right

Table 2-7. SUV

 Wheels Mud Engine V8 Brakes Standard Drive System All-Wheel Drive Can Drive Forward Can Stop Can Steer Left and Right Can Drive Uphill Can Tow a Boat

An SUV has wheels, brakes, and an engine. But it also has the ability to override the inherited attributes. Overriding is the ability to change how an attribute or behavior works for a class. This allows the SUV class to customize and control the inherited attributes and behaviors. Notice the SUV class has an engine, but it is a V8 engine. The class also has wheels, but they are mud wheels instead of standard wheels. The SUV class also has its own attributes and behaviors like an all-wheel drive system, the ability to drive uphill, and the ability to tow a boat. The child class is often referred to as a subclass of the parent class. In this case, the SUV class is a subclass of the car class.

Model, View, Controller

A closet is where you can keep all your shirts, pants, and shoes. A closet works best if you keep all of your items neatly positioned in different sections. This way when you need to grab a shirt quickly, you don’t have to dig through your pants and shoes as well. Keeping your closet clean and organized makes using it much easier. Also, if you want to replace all your shirts, you can remove all the old shirts without touching the pants or shoes.

The same goes for your code. Writing clean and well-organized code will save you exponentially more time than digging through a rat’s nest of code. The Model-View-Controller architecture helps to organize your code into three distinct parts (Figure 2-1).

Figure 2-1. Overview of Model-View-Controller

Keeping your code organized will make it easier when you have to go back and change a particular section. It will also make searching and navigating through your code much easier. It’s harder to change bad habits than it is to start new ones.

Model

The model portion of your code has to do with the data. For example, consider creating an application that stores all your friends’ contact information. The model portion would hold the phone numbers and addresses. To remember that the model is the data, think of a safe containing zeros and ones (Figure 2-2).

Figure 2-2. Model

View

The view portion of your code contains all the code related to the user interface. The view is like a picture frame; it holds and displays a picture, but it doesn’t know what picture it is displaying (Figure 2-3). Your view code should not be connected to the content it is displaying. This way, if the interface is changed, it doesn’t affect the content.

Figure 2-3. View

Controller

The controller portion contains all the logic and decision-making code. The controller is like a traffic cop; he directs the others where to go (Figure 2-4). It talks to the view and the model directly. The controller responds to taps on the screens, pulls data from the model, and tells the view what to display. The model and view never speak directly to each other. All communication goes through the controller.

Figure 2-4. Controller

Exercise: Hello World

It is time to start building your very first app. In this exercise, you will build a Hello World app (Figure 2-5). The app will have a button, which, when clicked, will display the words Hello World on the screen (Figure 2-6).

Figure 2-5. Completed Hello World exercise

Figure 2-6. Hello World shown

The first step is to open up Xcode. If you don’t see Xcode in your Dock, click the Spotlight search icon in the upper-right corner of your screen. Type in Xcode and click Top Hit (Figure 2-7).

Figure 2-7. Add Xcode to Dock

You will now see the Xcode icon on your Dock. Press the Control key and click the Xcode icon, hover over Options, and click “Keep in Dock.”

Once Xcode is loaded, a welcome screen will appear.

Click “Create a New Xcode Project.” Next, you will see the project template dialog (Figure 2-8). Select Single View Application and click Next. Then you will fill in some details for your new project (Figure 2-9).

Figure 2-8. Project template dialog

Figure 2-9. Project detail dialog

The first piece of information is called the Product Name. This will be used as the name of the project and the name of the folder for the project files. Enter HelloWorld as the Product Name. The Organization Name is the company or person developing this product. Your first and last name with no spaces will work well for now. The Organization Identifier is used to create the bundle identifier. The bundle identifier is like the Social Security number for your app. This is the unique identifier that separates your app from the other apps. Your first and last name with no spaces will work well here as well.

The last two items are very important. Throughout this book, you will be using Apple’s new programming language, Swift. Swift was announced in June of 2014 as the programming language of the future for iOS and OSX. Swift has many modern features that make a developer’s life much easier. Set the Language to Swift; you can safely assume you will be working with Swift for the rest of this book. Finally, leave Use Core Data unselected, and under devices, select iPhone. We will cover the Device options in Chapter 7.

The next dialog box will ask where you would like to save your project (Figure 2-10). It makes things easier if you create a dedicated folder for all of your apps. Click the Documents folder on the left sidebar and then click New Folder in the lower left of the dialog box (Figure 2-11).

Figure 2-10. Save Dialog

Figure 2-11. New Folder name entry

Name the folder “Programming” and click Create. Finally, leave “Create Git Repository on My Mac” unselected and click Create (Figure 2-12).

Figure 2-12. Project details

You will see your Xcode project open.

The left sidebar is called the Project Navigator (Figure 2-13). The Project Navigator works like Finder on your Mac. It provides an easy way to explore and open the files in your project. The folders inside the Project Navigator are called groups and are not actual folders inside your Mac’s file system.

Figure 2-13. Project Navigator

The middle portion of the screen is called the Editor. The Editor displays whichever file is selected in the Project Navigator. Figure 2-14 shows the project details because the project is selected in the Project Navigator on the left.

Figure 2-14. Editor

The right sidebar is called the Inspector (Figure 2-15). The Inspector is where details for whichever file is shown in the Editor can be changed. The Inspector is dynamic and will change depending on the file you have selected inside the Editor.

Figure 2-15. Inspector

The top portion of the Xcode window is called the Toolbar (Figure 2-16). It looks similar to the Toolbar inside of iTunes. In the upper left of the Toolbar, you will find the Play and Stop buttons. These buttons are used for running and testing your app. In the middle, you will find the Activity Viewer. This box will provide updates as your code is being processed. In the upper-right corner, you will find two sets of buttons.

Figure 2-16. Toolbar

NOTE

Remember, some of the buttons and screenshots may differ based on your version of OSX. All screenshots in this book are taken using, OSX Yosemite (10.10), but descriptions will be provided for those using OSX Mavericks (10.9).

The first set of buttons controls the Editor (Figure 2-17). The first button, with horizontal lines on it, will present the Standard Editor. The Standard Editor is the single view editor you typically see when you first start a new project. The next button, with interlocking circles on it, is called theAssistant Editor. If you are running OSX Mavericks (10.9), this button will have a small tuxedo on it instead of interlocking circles. The Assistant Editor will open another editor next to the Standard Editor and show files associated with the file currently displayed inside the Standard Editor. Think of the Assistant Editor like your butler, always at your side with the files you need. Finally, the last button is called the Version Editor. This view is used to track and analyze changes made to your project. For most cases, keep this on Standard Editor unless specifically told otherwise.

Figure 2-17. Editor controls

The next set of buttons, in the upper right of your screen, are used to hide or show the three major sections of Xcode (Figure 2-18). The first button will hide or show the Project Navigator. The second button will hide or show the Debugger. The Debugger will be discussed in Chapter 6. Finally, the third button will hide or show the Inspector. These buttons are especially helpful if you are working on a small screen.

Figure 2-18. View controls

Next, click Main.storyboard inside the Project Navigator.

The Editor is now displaying the Storyboard for your application (Figure 2-19). Storyboards are used to represent the user interface, or interface, for short. Storyboards hold all the buttons, graphics, and design elements for the application. Storyboards can stretch and scale to fit any size screen from iPhone to iPad.

Figure 2-19. Main.storyboard

Your first app will run only on iPhone; click the first tab at the top of the Inspector. The tab looks like a piece of paper with a folded corner. About halfway down, deselect the Use Auto Layout checkbox (Figure 2-20), then select Disable Size Classes. Auto Layout is a set of tools used for multiple screen sizes and will be covered in Chapter 7.

Figure 2-20. Disable size classes

About halfway down on the Inspector is a small toolbar; click the third item from the left. The icon looks like a small circle with a square inside it. The icon will reveal the Object Library when you hover over it (Figure 2-21). Click the Object Library icon, and you will notice that the bottom of the Inspector will change.

Figure 2-21. Object Library icon

The Object Library holds the user interface elements you will use in your design (Figure 2-22). Scroll down through the Object Library until you see Label. A Label is a user interface element used to display text to the user. This text is only readable; the user cannot change this text. Click and drag a Label over the Storyboard (Figure 2-23).

Figure 2-22. Object Library

Figure 2-23. New Label

When you drag an element over a Storyboard, Xcode will help you snap the element to the horizontal center and vertical center. You may recognize this kind of assistance from desktop applications like PowerPoint or Keynote. Position the Label in the center of the screen. You will see the two guidelines when the element is in the absolute center (Figure 2-24).

Figure 2-24. Centered Label

Next, select the Label and grab the white dot in the upper-right corner of the Label. Drag toward the upper-right corner of your screen. A small box will pop up displaying the size of your label. Drag until the Label is at least 150 pt wide by 30 pt tall and then release it (Figure 2-25). Recenter the Label as necessary.

Figure 2-25. Resized Label

Once you have positioned your Label on the Storyboard, take a look at the Inspector toolbar.

Along the top of the Inspector is a small toolbar with six icons (Figure 2-26). Each of these icons represents a different section of the Inspector. Look at the fourth icon from the left. The icon looks like a downward facing arrow, and it reveals “Show the Attributes Inspector” when you hover over it. Click the Attributes Inspector icon. The Attributes Inspector allows you to change the values for attributes of the selected element on the Storyboard (Figure 2-27).

Figure 2-26. Attributes Inspector icon

Figure 2-27. Attributes Inspector for Label

Click the Label and notice the options available in the Attributes Inspector. You can verify the Label is selected because the element will be surrounded by white dots, or you can look at the upper-left corner of the Attributes Inspector and see the word “Label.”

Labels have many properties that you can change. The text attribute holds the string displayed by the Label. Underneath the Style drop-down menu is a text box with the word “Label” inside of it. Double-click the text and replace it with “????”. Press Return (Figure 2-28).

Figure 2-28. Updated Label

The color attribute will change the color of the text displayed by the Label. Click the drop-down arrows next to the word “Color.” Scroll down and click Other.

This will present a Color Picker. Your Color Picker may look entirely black. If this is the case, grab the horizontal slider and slide it to the left. You will see a rainbow of colors (Figure 2-29). Click and drag your cursor around in the Color Picker and watch the color of your text change. Pick your color and close the Color Picker.

Figure 2-29. Color Picker

Turn your attention back to the Attributes Inspector and find the font attribute. Click the small box with a T inside of it. This will display a pop-up window. Click the drop-down arrows next to the font attribute and select System Bold (Figure 2-30).

Figure 2-30. Font update

Click the small up arrow next to the size box and change the font size to “20.” Click Done when you’re finished.

Just below the font attribute is the alignment attribute. Click the middle button to center-align the Label’s text (Figure 2-31). You may want to drag and recenter your Label after this change.

Figure 2-31. Alignment update

Next, head back over to the Object Library at the bottom of the Inspector (Figure 2-32). Scroll down and drag a Button onto the Storyboard. Position the Button just above the Label (Figure 2-33).

Figure 2-32. Object Library

Figure 2-33. New Button

Double-click the Button and type Go. Double-clicking is a shortcut for changing the text attribute inside the Inspector.

Remember to always save your work. If you see a dark or dirty icon next to a filename in the Project Navigator, that means changes have been made but have not been saved (Figure 2-34). Click File→Save from the top menu bar to save your project (Figure 2-35). You can also save by pressing Command+S.

Figure 2-34. Dirty icon

Figure 2-35. Save

You have finished designing your application; now you need to add some code that controls your application. But first, you must connect the interface elements to the code.

Start by hiding the Inspector. To hide the Inspector, look in the upper-right corner of your screen. Click the square button with a blue stripe on the right side of it. The blue stripe will turn to black, and the Inspector will be hidden (Figure 2-36).

Next, move your mouse to the left of the view buttons and click the button with interlocking circles on it. If you are running OSX Mavericks (10.9), this button will have a small tuxedo on it instead of interlocking circles. A new Editor will appear on the right side of your screen. The Assistant Editor will detect what file you are working on and then display a helpful related file (Figure 2-37).

Figure 2-36. Hidden Inspector

Figure 2-37. Assistant Editor

You may notice that it is hard to see the Storyboard, because it is hidden by another list of elements. This list of elements is called the Document Outline. The Document Outline provides a quick and easy way to select any element on the Storyboard (Figure 2-38).

Figure 2-38. Document Outline

Look at the bottom-left corner of the Standard Editor and click the small square button with a stripe. This will hide the Document Outline (Figure 2-39).

Figure 2-39. Hidden Document Outline

Storyboards

The Storyboard file is the view file in the Model-View-Controller paradigm. The Assistant Editor is currently displaying ViewController.swift. ViewController.swift is the controller in Model-View-Controller, and it holds all the logic for the interface you just created. Before you connect your user interface elements to your controller, you need to understand the two different types of connections between a view and a controller.

The first type of connection is an action. An action is triggered when a user taps, swipes, or makes a specified gesture on the interface. The action then sends an alert to the controller, where the controller can decide how to react. Actions are commonly used with Buttons. For example, a Button is tapped on the interface, and the controller is alerted. The controller can then choose what to do in response to the action.

The other type of connection is called an outlet. An outlet works in the opposite direction as an action. An outlet is a direct link to the view from the controller and is used to retrieve or set information from an interface element. For example, a Label on the interface has a corresponding outlet, allowing the controller to read and set the Label’s text.

In order to create these connections between your view and controller, you will draw a line from one side to the other. Select the Label on the Storyboard (Figure 2-40).

Figure 2-40. Storyboard with Assistant Editor

Now hold the Control key on your Mac; this is not the same as the Command key. The Control key will be on the left side of your keyboard next to the Option key. While holding the Control key, click and drag from the Label over to the Assistant Editor (Figure 2-41).

Figure 2-41. Control-drag connection

Drag your cursor immediately under the following words:

ViewController : UIViewController

When you see a dark blue horizontal line appear under your cursor, release your mouse. A pop-up window will appear asking you to enter more information about the connection (Figure 2-42).

Figure 2-42. Pop-up connection dialog

The connection type is grayed out, and the outlet is selected. This is because a Label cannot create an action. For example, users cannot click a Label to do something. In the name field, enter helloLabel (Figure 2-43).

Figure 2-43. Completed pop-up connection dialog

TIP

To use camel-casing, remove all spaces and capitalize each word. However, do not capitalize the first letter of a word. For example, number of years would become numberOfYears.

Always use camel-casing with outlet and action names.

It is best practice to state the class of element you are using in the name, in this case, a Label. This makes it much easier to tell which variable name goes to which element when you are inside the controller. After you have entered the name, click Connect.

Click the Button in the Storyboard (Figure 2-44) and Control-drag from it over to the same spot in the Assistant Editor. When you see the horizontal blue line, release your drag (Figure 2-45).

Figure 2-44. Selected Button

Figure 2-45. Control-drag connection

A connection pop-up dialog box will appear on the screen. Change the connection to Action. You will notice a new Event option will be displayed. This is the event that will trigger the action from the interface. Leave it on Touch Up Inside and enter the name goTapped (Figure 2-46).

Figure 2-46. Completed pop-up connection dialog

It is best practice to name any action after the event that triggered it. In this case, Touch Up Inside means to tap and release your finger within the coordinates of the button. Be sure your connection is set to Action and click Connect.

The connections you created automatically generated some code inside the ViewController.swift file (Figure 2-47). You will notice the keywords @IBAction or @IBOutlet next to each connection.

Figure 2-47. ViewController.swift

Place your cursor at the end of the line that reads:

@IBAction func goTapped (sender : AnyObject) {

Then between the open and closed braces, write the following line of code:

helloLabel.text = "Hello World"

This is the only line of code you will write for this application. The variable helloLabel refers to the Label on the interface. Placing a dot next to a variable provides a list of the methods and attributes for this object. In this case, you are working with the text attribute. The text attribute asks for a string as input. The text attribute will display the provided string inside the Label. You use the equals sign to set helloLabel’s text attribute to "Hello World" (Figure 2-48).

Figure 2-48. Hello World text

Now for the moment of truth. Click the Play button in the upper-left corner of your screen. You will see the iOS Simulator application launch with your new app. The iOS Simulator is a virtual iOS device that can be configured to be any iPhone or iPad size. To run your apps on your own iOS device, you will need to register as an Apple Developer. This book will cover running apps on your device in Chapter 10.

The iOS Simulator may take a little while to load the first time (Figure 2-49). However after the first time, the iOS Simulator will load faster. If you don’t see a virtual iPhone on your screen, check your Dock for the iOS Simulator icon. Once you see the app running on the iOS Simulator, click the Go button and bask in the beauty of your first app (Figure 2-50)!

Figure 2-49. Hello World launch

Figure 2-50. Hello World complete

If you made it through with no issues, congratulations. Now try to complete the entire exercise on your own without looking at this book. Memorizing the basics will make building apps easier going forward.

Don’t worry if you received an error, a warning, or your app did not run as expected. The best way to learn is to make mistakes. Practice makes perfect. A sample version of the project is available on AppSchool.com/book. Download it, compare it, and try, try again. Don’t be afraid to start the exercise over and walk through it until you get it right.

﻿