iOS Programming: The Big Nerd Ranch Guide (2014)

Introduction

As an aspiring iOS developer, you face three basic hurdles:

·        You must learn the Objective-C language. Objective-C is a small and simple extension to the C language. After the first four chapters of this book, you will have a working knowledge of Objective-C.

·        You must master the big ideas. These include things like memory management techniques, delegation, archiving, and the proper use of view controllers. The big ideas take a few days to understand. When you reach the halfway point of this book, you will understand these big ideas.

·        You must master the frameworks. The eventual goal is to know how to use every method of every class in every framework in iOS. This is a project for a lifetime: there are over 3000 methods and more than 200 classes available in iOS. To make things even worse, Apple adds new classes and new methods with every release of iOS. In this book, you will be introduced to each of the subsystems that make up the iOS SDK, but we will not study each one deeply. Instead, our goal is to get you to the point where you can search and understand Apple’s reference documentation.

We have used this material many times at our iOS Development Bootcamp at Big Nerd Ranch. It is well-tested and has helped hundreds of people become iOS application developers. We sincerely hope that it proves useful to you.

Prerequisites

This book assumes that you are already motivated to learn to write iOS apps. We will not spend any time convincing you that the iPhone, the iPad, and the iPod touch are compelling pieces of technology.

We also assume that you know the C programming language and something about object-oriented programming. If this is not true, you should probably start with an introductory book on C and Objective-C, such as Objective-C Programming: The Big Nerd Ranch Guide.

What has Changed in the Fourth Edition?

This edition assumes that the reader is using Xcode 5 and running applications on an iOS 7 device or simulator.

We have adopted a more modern style of Objective-C in this edition. We use properties, dot notation, auto-synthesized instance variables, the new literals, and subscripting extensively. We also use blocks more.

Apple continues to evolve iOS, and we have eagerly added coverage of block-based animations, Auto Layout, and NSURLSession to the book.

Besides these obvious changes, we made thousands of tiny improvements that were inspired by questions from our readers and our students. Every chapter of this book is just a little better than the corresponding chapter from the third edition.

Our Teaching Philosophy

This book will teach you the essential concepts of iOS programming. At the same time, you will type in a lot of code and build a bunch of applications. By the end of the book, you will have knowledge and experience. However, all the knowledge should not (and, in this book, will not) come first. That is sort of the traditional way we have all come to know and hate. Instead, we take a learn-while-doing approach. Development concepts and actual coding go together.

Here is what we have learned over the years of teaching iOS programming:

·        We have learned what ideas people must grasp to get started programming, and we focus on that subset.

·        We have learned that people learn best when these concepts are introduced as they are needed.

·        We have learned that programming knowledge and experience grow best when they grow together.

·        We have learned that “going through the motions” is much more important than it sounds. Many times we will ask you to start typing in code before you understand it. We realize that you may feel like a trained monkey typing in a bunch of code that you do not fully grasp. But the best way to learn coding is to find and fix your typos. Far from being a drag, this basic debugging is where you really learn the ins and outs of the code. That is why we encourage you to type in the code yourself. You could just download it, but copying and pasting is not programming. We want better for you and your skills.

What does this mean for you, the reader? To learn this way takes some trust. And we appreciate yours. It also takes patience. As we lead you through these chapters, we will try to keep you comfortable and tell you what is happening. However, there will be times when you will have to take our word for it. (If you think this will bug you, keep reading – we have some ideas that might help.) Do not get discouraged if you run across a concept that you do not understand right away. Remember that we are intentionally not providing all the knowledge you will ever need all at once. If a concept seems unclear, we will likely discuss it in more detail later when it becomes necessary. And some things that are not clear at the beginning will suddenly make sense when you implement them the first (or the twelfth) time.

People learn differently. It is possible that you will love how we hand out concepts on an as-needed basis. It is also possible that you will find it frustrating. In case of the latter, here are some options:

·        Take a deep breath and wait it out. We will get there, and so will you.

·        Check the index. We will let it slide if you look ahead and read through a more advanced discussion that occurs later in the book.

·        Check the online Apple documentation. This is an essential developer tool, and you will want plenty of practice using it. Consult it early and often.

·        If Objective-C or object-oriented programming concepts are giving you a hard time (or if you think they will), you might consider backing up and reading our Objective-C Programming: The Big Nerd Ranch Guide.

How to Use This Book

This book is based on the class we teach at Big Nerd Ranch. As such, it was designed to be consumed in a certain manner.

Set yourself a reasonable goal, like “I will do one chapter every day.” When you sit down to attack a chapter, find a quiet place where you will not be interrupted for at least an hour. Shut down your email, your Twitter client, and your chat program. This is not a time for multi-tasking; you will need to concentrate.

Do the actual programming. You can read through a chapter first, if you like. But the real learning comes when you sit down and code as you go. You will not really understand the idea until you have written a program that uses it and, perhaps more importantly, debugged that program.

A couple of the exercises require supporting files. For example, in the first chapter you will need an icon for your Quiz application, and we have one for you. You can download the resources and solutions to the exercises from http://www.bignerdranch.com/solutions/iOSProgramming4ed.zip.

There are two types of learning. When you learn about the Peloponnesian War, you are simply adding details to a scaffolding of ideas that you already understand. This is what we will call “Easy Learning.” Yes, learning about the Peloponnesian War can take a long time, but you are seldom flummoxed by it. Learning iOS programming, on the other hand, is “Hard Learning,” and you may find yourself quite baffled at times, especially in the first few days. In writing this book, we have tried to create an experience that will ease you over the bumps in the learning curve. Here are two things you can do to make the journey easier:

·        Find someone who already knows how to write iOS applications and will answer your questions. In particular, getting your application onto the device the first time is usually very frustrating if you are doing it without the help of an experienced developer.

·        Get enough sleep. Sleepy people do not remember what they have learned.

Using an eBook

If you are reading this book on a Kindle or Kindle for iPad, we want to point out that reading the code may be tricky at times. Longer lines of code will wrap to a second line based on the current font size. This bothers us because we are really conscientious at Big Nerd Ranch about the way our code appears on the page. Clear visual patterns in code make that code easier to understand.

Therefore, when you get to the point where you are actually typing in code, we suggest opening the book on your Mac in Kindle for Mac, a free application you can download from Amazon.com. Make the application window large enough so that you can see the code with no wrapping lines. In Kindle for Mac’s larger window, you will also be able to see the figures in full detail. Using your Kindle or iPad together with Kindle for Mac will give you the best of both worlds: convenient, portable reading and the chance to examine the code in its intended form.

How This Book is Organized

In this book, each chapter addresses one or more ideas of iOS development through discussion and hands-on practice. For more coding practice, most chapters include challenge exercises. We encourage you to take on at least some of these. They are excellent for firming up the concepts introduced in the chapter and making you a more confident iOS programmer. Finally, most chapters conclude with one or two “For the More Curious” sections that explain certain consequences of the concepts that were introduced earlier.

Chapter 1 introduces you to iOS programming as you build and deploy a tiny application. You will get your feet wet with Xcode and the iOS simulator along with all the steps for creating projects and files. The chapter includes a discussion of Model-View-Controller and how it relates to iOS development.

Chapters 2 and 3 provide an overview of Objective-C and memory management. Although you will not create an iOS application in these two chapters, you will build and debug a tool called RandomItems to ground you in these concepts.

In Chapters 4 and 5, you will begin focusing on the iOS user interface as you learn about views and the view hierarchy and create an application called Hypnosister.

Chapters 6 and 7 introduce view controllers for managing user interfaces with the HypnoNerd application. You will get practice working with views and view controllers as well as navigating between screens using a tab bar. You will also get plenty of experience with the important design pattern of delegation as well as working with protocols, the debugger, and setting up local notifications.

Chapter 8 introduces the largest application in the book – Homepwner. (By the way, “Homepwner” is not a typo; you can find the definition of “pwn” at www.urbandictionary.com.) This application keeps a record of your possessions in case of fire or other catastrophe. Homepwner will take fourteen chapters to complete.

In Chapters 8, 9, and 19, you will build experience with tables. You will learn about table views, their view controllers, and their data sources. You will learn how to display data in a table, how to allow the user to edit the table, and how to improve the interface.

Chapter 10 builds on the navigation experience gained in Chapter 6. You will learn how to use UINavigationController and you will give Homepwner a drill-down interface and a navigation bar.

In Chapter 11, you will learn how to take pictures with the camera and how to display and store images in Homepwner. You will use NSDictionary and UIImagePickerController.

In Chapters 12 and 13, you will set Homepwner aside for a bit to create a drawing application named TouchTracker to learn about touch events. You will see how to add multi-touch capability and how to use UIGestureRecognizer to respond to particular gestures. You will also get experience with the first responder and responder chain concepts and more practice with NSDictionary.

In Chapter 14, you will learn how to use debug gauges, Instruments, and the static analyzer to optimize the performance of TouchTracker.

In Chapters 15 and 16, you will make Homepwner a universal application – an application that runs natively on both the iPhone and the iPad. You will also work with Auto Layout to build an interface that will appear correctly on any screen size.

In Chapter 17, you will learn about handling rotation and using UIPopoverController for the iPad and modal view controllers.

Chapter 18 delves into ways to save and load data. In particular, you will archive data in the Homepwner application.

In Chapter 20, you will update Homepwner to use Dynamic Type to support different font sizes that a user may prefer.

Chapter 21 takes another break from Homepwner and introduces web services as you create the Nerdfeed application. This application fetches and parses an RSS feed from a server using NSURLConnection and NSXMLParser. Nerdfeed will also display a web page in a UIWebView.

In Chapter 22, you will learn about UISplitViewController and add a split view user interface to Nerdfeed to take advantage of the iPad’s larger screen size.

Chapter 23 returns to the Homepwner application with an introduction to Core Data. You will change Homepwner to store and load its data using an NSManagedObjectContext.

In Chapter 24, you will add state restoration to Homepwner to let users return to the application right where they left off – no matter how long they are away.

Chapter 25 introduces the concepts and techniques of internationalization and localization. You will learn about NSLocale, strings tables, and NSBundle as you localize parts of Homepwner.

In Chapter 26, you will use NSUserDefaults to save user preferences in a persistent manner. This chapter will complete the Homepwner application.

Chapter 27 introduces the Core Animation framework with a brief return to the HypnoNerd application to implement animations.

Chapter 28 introduces building applications using storyboards. You will piece together an application using UIStoryboard and learn more about the pros and cons of using storyboards.

Style Choices

This book contains a lot of code. We have attempted to make that code and the designs behind it exemplary. We have done our best to follow the idioms of the community, but at times we have wandered from what you might see in Apple’s sample code or code you might find in other books. You may not understand these points now, but it is best that we spell them out before you commit to reading this book:

·         We typically create view controllers programmatically. Some programmers will instantiate view controllers inside XIB files or in a storyboard. We will discuss storyboards and demonstrate their use a little, but, in reality, we seldom use them in our projects at Big Nerd Ranch.

·         We will nearly always start a project with the simplest template project: the empty application. When your app works, you will know it is because of your efforts – not because that behavior was built into the template.

Typographical Conventions

To make this book easier to read, certain items appear in certain fonts. Class names, method names, and function names appear in a bold, fixed-width font. Class names start with capital letters and method names start with lowercase letters. In this book, method and function names are formatted the same for simplicity’s sake. For example, “In the loadView method of the BNRRexViewController class, use the NSLog function to print the value to the console.”

Variables, constants, types, and file names appear in a fixed-width font but are not bold. So you will see, “The variable fido will be of type float. Initialize it to M_PI.”

Menu choices and buttons appear in the default font in a slight reduced size. For example, “Open Xcode and select New Project... from the File menu. Select Window-based Application and then click Choose....”

All code blocks are in a fixed-width font. Code that you need to type in is always bold. For example, in the following code, you would type in everything but the first and last lines. (Those lines are already in the code and appear here to let you know where to add the new stuff.)

@interface BNRQuizViewController ()

@property (nonatomic, weak) IBOutlet UILabel *questionLabel;

@property (nonatomic, weak) IBOutlet UILabel *answerLabel;

@end

Necessary Hardware and Software

You can only develop iOS apps on an Intel Mac. You will need to download Apple’s iOS SDK, which includes Xcode (Apple’s Integrated Development Environment), the iOS simulator, and other development tools.

You should join Apple’s iOS Developer Program, which costs $99/year, for three reasons:

·        Downloading the latest developer tools is free for members.

·        Only signed apps will run on a device, and only members can sign apps. If you want to test your app on your device, you will need to join.

·        You cannot put an app in the store until you are a member.

If you are going to take the time to work through this entire book, membership in the iOS Developer Program is, without question, worth the cost. Go to http://developer.apple.com/programs/ios/ to join.

What about iOS devices? Most of the applications you will develop in the first half of the book are for the iPhone, but you will be able to run them on an iPad. On the iPad screen, iPhone applications appear in an iPhone-sized window. Not a compelling use of the iPad, but that is okay when you are starting with iOS. In these first chapters, you will be focused on learning the fundamentals of the iOS SDK, and these are the same across iOS devices. Later in the book, we will look at some iPad-only options and how to make applications run natively on both iOS device families.

Excited yet? Good. Let’s get started.