Objective-C�Programming
THE�BIG�NERD�RANCH�GUIDE
AARON HILLEGASS
Objective-C Programming
Objective-C Programming: The Big Nerd Ranch Guide
by Aaron Hillegass
Copyright © 2011 Big Nerd Ranch, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and
permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system,
or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For
information regarding permissions, contact
Big Nerd Ranch, Inc.
154 Krog Street
Suite 100
Atlanta, GA 30307
(404) 478-9005
http://www.bignerdranch.com/
[email protected]The 10-gallon hat with propeller logo is a trademark of Big Nerd Ranch, Inc.
Exclusive worldwide distribution of the English edition of this book by
Pearson Technology Group
800 East 96th Street
Indianapolis, IN 46240 USA
http://www.informit.com
The authors and publisher have taken care in writing and printing this book but make no expressed or implied
warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental
or consequential damages in connection with or arising out of the use of the information or programs contained
herein.
App Store, Apple, Cocoa, Cocoa Touch, Instruments, Interface Builder, iOS, iPad, iPhone, iTunes, iTunes Store,
Mac, Mac OS, Objective-C, and Xcode are trademarks of Apple, Inc., registered in the U.S. and other countries.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the
designations have been printed with initial capital letters or in all capitals.
ISBN-10 0321706285
ISBN-13 978-0321706287
Library of Congress Control Number: 2011931707
Second printing, January 2012
Acknowledgments
It is a great honor that I get to work with such amazing people. Several of them put a lot of time and
energy into making this book great. I’d like to take this moment to thank them.
• Mikey Ward wrote several chapters of this book including Your First iOS Application, Your First
Cocoa Program, and Blocks. If I were a nicer boss, I would have put his name on the cover.
• The other instructors who teach the Objective-C materials fed us with a never-ending stream of
suggestions and corrections. They are Scott Ritchie, Mark Fenoglio, Brian Hardy, Christian Keur,
and Alex Silverman.
• My tireless editor, Susan Loper, took my stream-of-consciousness monologue that stumbled across
everything a programmer needs to know and honed it into an approachable primer.
• Several technical reviewers helped me find and fix flaws. They are James Majors, Mark Dalrymple,
Scott Steinman, Bart Hoffman, Bolot Kerimbaev, and Nate Chandler.
• Ellie Volckhausen designed the cover.
• Chris Loper at IntelligentEnglish.com designed and produced the EPUB and Kindle versions.
• The amazing team at Pearson Technology Group patiently guided us through the business end of
book publishing.
iii
This page intentionally left blank
&('
! 0 % !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!K ) ( *!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1
>@ "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1
+ *+ *!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! .
+ & & '' + *!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!.
!K ) , # '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!2
G" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 2
0 + A !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 2
B + L!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 6
+ ) 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!!!!!!!!!!!!!!!!!!!!!!!!!!! .6
( & !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -
Objective-C Programming
continue ........................................................................................................ 52
The do-while loop ........................................................................................... 53
Challenge ...................................................................................................... 54
8. Addresses and Pointers ......................................................................................... 55
Getting addresses ............................................................................................ 55
Storing addresses in pointers ............................................................................. 56
Getting the data at an address ........................................................................... 57
How many bytes? ........................................................................................... 57
NULL ........................................................................................................... 58
Stylish pointer declarations ............................................................................... 59
Challenges ..................................................................................................... 59
9. Pass By Reference ............................................................................................... 61
Writing pass-by-reference functions ................................................................... 62
Avoid dereferencing NULL ............................................................................... 64
10. Structs ............................................................................................................. 65
Challenge ...................................................................................................... 66
11. The Heap ......................................................................................................... 69
III. Objective-C and Foundation ........................................................................................ 73
12. Objects ............................................................................................................ 75
Creating and using your first object .................................................................... 75
Message anatomy ............................................................................................ 77
Objects in memory .......................................................................................... 79
id ................................................................................................................. 79
Challenge ...................................................................................................... 80
13. More Messages ................................................................................................. 81
Nesting message sends ..................................................................................... 81
Multiple arguments ......................................................................................... 82
Sending messages to nil ................................................................................... 82
Challenge ...................................................................................................... 83
14. NSString .......................................................................................................... 85
Challenge ...................................................................................................... 86
15. NSArray .......................................................................................................... 87
NSMutableArray ............................................................................................. 89
Challenges ..................................................................................................... 90
16. Developer Documentation ................................................................................... 93
Reference pages .............................................................................................. 94
Quick Help .................................................................................................... 96
Other options and resources .............................................................................. 98
17. Your First Class ............................................................................................... 101
Accessor methods .......................................................................................... 103
Dot notation ................................................................................................. 104
Properties ..................................................................................................... 105
self ............................................................................................................. 106
Multiple files ................................................................................................ 106
Challenge ..................................................................................................... 106
18. Inheritance ...................................................................................................... 109
Overriding methods ....................................................................................... 112
super ........................................................................................................... 113
vi
Objective-C Programming
Challenge ..................................................................................................... 113
19. Object Instance Variables .................................................................................. 115
Object ownership and ARC ............................................................................. 117
Creating the Asset class .......................................................................... 118
Adding a to-many relationship to Employee ............................................... 119
Challenge ..................................................................................................... 123
20. Preventing Memory Leaks ................................................................................. 125
Retain cycles ................................................................................................ 127
Weak references ............................................................................................ 129
Zeroing of weak references ............................................................................. 130
For the More Curious: Manual reference counting and ARC History ....................... 131
Retain count rules ................................................................................. 133
21. Collection Classes ............................................................................................ 135
NSArray/NSMutableArray .............................................................................. 135
Immutable objects ................................................................................. 135
Sorting ................................................................................................ 136
Filtering ............................................................................................... 137
NSSet/NSMutableSet ..................................................................................... 138
NSDictionary/NSMutableDictionary ................................................................. 140
C primitive types ........................................................................................... 142
Collections and nil ........................................................................................ 142
Challenge ..................................................................................................... 143
22. Constants ........................................................................................................ 145
Preprocessor directives ................................................................................... 145
#include and #import ..................................................................................... 146
#define ........................................................................................................ 146
Global variables ............................................................................................ 147
enum ................................................................................................... 148
#define vs global variables .............................................................................. 149
23. Writing Files with NSString and NSData .............................................................. 151
Writing an NSString to a file .......................................................................... 151
NSError ....................................................................................................... 152
Reading files with NSString ............................................................................ 153
Writing an NSData object to a file ................................................................... 154
Reading an NSData from a file ........................................................................ 155
24. Callbacks ........................................................................................................ 157
Target-action ................................................................................................. 157
Helper objects ............................................................................................... 160
Notifications ................................................................................................. 163
Which to use? .............................................................................................. 164
Callbacks and object ownership ....................................................................... 164
25. Protocols ........................................................................................................ 167
26. Property Lists .................................................................................................. 171
Challenge ..................................................................................................... 173
IV. Event-Driven Applications ......................................................................................... 175
27. Your First iOS Application ................................................................................ 177
Getting started with iTahDoodle ....................................................................... 177
BNRAppDelegate .......................................................................................... 179
vii
Objective-C Programming
Adding a C helper function ............................................................................. 180
Objects in iTahDoodle .................................................................................... 181
Model-View-Controller ................................................................................... 182
The application delegate ................................................................................. 183
Setting up views ........................................................................................... 184
Running on the iOS simulator ................................................................. 185
Wiring up the table view ................................................................................ 186
Adding new tasks .......................................................................................... 189
Saving task data .................................................................................... 189
For the More Curious: What about main()? ........................................................ 190
28. Your First Cocoa Application ............................................................................. 191
Edit BNRDocument.h .................................................................................... 192
A look at Interface Builder ............................................................................. 193
Edit BNRDocument.xib .................................................................................. 194
Making connections ....................................................................................... 198
Revisiting MVC ............................................................................................ 202
Edit BNRDocument.m ................................................................................... 202
Challenges ................................................................................................... 204
V. Advanced Objective-C ................................................................................................ 205
29. init ................................................................................................................ 207
Writing init methods ...................................................................................... 207
A basic init method ....................................................................................... 208
Using accessors ............................................................................................ 209
init methods that take arguments ...................................................................... 210
Deadly init methods ....................................................................................... 215
30. Properties ....................................................................................................... 217
Property attributes ......................................................................................... 218
Mutability ............................................................................................ 218
Lifetime specifiers ................................................................................. 218
Advice on atomic vs. nonatomic .............................................................. 220
Key-value coding .......................................................................................... 221
Non-object types ................................................................................... 222
31. Categories ....................................................................................................... 225
32. Blocks ............................................................................................................ 227
Defining blocks ............................................................................................. 227
Using blocks ................................................................................................ 228
Declaring a block variable ...................................................................... 228
Assigning a block .................................................................................. 229
Passing in a block ................................................................................. 230
typedef ........................................................................................................ 233
Return values ................................................................................................ 233
Memory management ..................................................................................... 234
The block-based future ................................................................................... 235
Challenges ................................................................................................... 235
Anonymous block ................................................................................. 235
NSNotificationCenter ............................................................................. 236
VI. Advanced C ............................................................................................................ 237
33. Bitwise Operations ........................................................................................... 239
viii
Objective-C Programming
Bitwise-OR .................................................................................................. 240
Bitwise-AND ................................................................................................ 241
Other bitwise operators .................................................................................. 242
Exclusive OR ....................................................................................... 242
Complement ......................................................................................... 243
Left-shift .............................................................................................. 243
Right-shift ............................................................................................ 244
Using enum to define bit masks ....................................................................... 245
More bytes ................................................................................................... 245
Challenge ..................................................................................................... 245
34. C Strings ........................................................................................................ 247
char ............................................................................................................ 247
char * ......................................................................................................... 248
String literals ................................................................................................ 250
Converting to and from NSString ..................................................................... 251
Challenge ..................................................................................................... 252
35. C Arrays ........................................................................................................ 253
36. Command-Line Arguments ................................................................................ 257
37. Switch Statements ............................................................................................ 261
Next Steps ................................................................................................................... 263
Index ........................................................................................................................... 265
ix
This page intentionally left blank
Part I
Getting Started
This page intentionally left blank
1
You and This Book
Let’s talk about you for a minute. You want to write applications for iOS or Mac OS X, but you haven’t
done much (or any) programming in the past. Your friends have raved about my other books (iOS
Programming: The Big Nerd Ranch Guide and Cocoa Programming for Mac OS X), but they are
written for experienced programmers. What should you do? Read this book.
There are similar books, but this one is the one you should read. Why? I’ve been teaching people
how to write applications for iOS and the Mac for a long time now, and I’ve identified what you need
to know at this point in your journey. I’ve worked hard to capture that knowledge and dispose of
everything else. There is a lot of wisdom and very little fluff in this book.
My approach is a little unusual. Instead of simply trying to get you to understand the syntax of
Objective-C, I’ll show you how programming works and how experienced programmers think about it.
Because of this approach, I’m going to cover some heavy ideas early in the book. You should not
expect this to be an easy read. In addition, nearly every idea comes with a programming experiment.
This combination of learning concepts and immediately putting them into action is the best way to
learn programming.
C and Objective-C
When you run a program, a file is copied from the file system into memory (RAM), and the
instructions in that file are executed by your computer. Those instructions are inscrutable to humans.
So, humans write computer programs in a programming language. The very lowest-level programming
language is called assembly code. In assembly code, you describe every step that the CPU (the
computer’s brain) must take. This code is then transformed into machine code (the computer’s native
tongue) by an assembler.
Assembly language is tediously long-winded and CPU-dependent (because the brain of your latest
iMac can be quite different from the brain of your well-loved, well-worn PowerBook). In other words,
if you want to run the program on a different type of computer, you will need to rewrite the assembly
code.
To make code that could be easily moved from one type of computer to another, we developed “high-
level languages.” With high-level languages, instead of thinking about a particular CPU, you could
express the instructions in a general way, and a program (called a compiler) would transform that code
into highly-optimized, CPU-specific machine code. One of these languages is C. C programmers write
code in the C language, and a C compiler then converts the C code into machine code.
3
Chapter 1 You and This Book
The C language was created in the early 1970s at AT&T. The Unix operating system, which is the
basis for Mac OS X and Linux, was written in C with a little bit of assembly code for very low-level
operations. The Windows operating system is also mostly written in C.
The Objective-C programming language is based on C, but it adds support for object-oriented
programming. Objective-C is the programming language that is used to write applications for Apple’s
iOS and Mac OS X operating systems.
How this book works
In this book, you will learn enough of the C and Objective-C programming languages to learn to
develop applications for the Mac or for iOS devices.
Why am I going to teach you C first? Every effective Objective-C programmer needs a pretty deep
understanding of C. Also, a lot of the ideas that look complicated in Objective-C have very simple
roots in C. I will often introduce an idea using C and then push you toward mastery of the same idea in
Objective-C.
This book was designed to be read in front of a Mac. You will read explanations of ideas and carry out
hands-on experiments that will illustrate those ideas. These experiments aren’t optional. You won’t
really understand the book unless you do them. The best way to learn programming is to type in code,
make typos, fix your typos, and become physically familiar with the patterns of the language. Just
reading code and understanding the ideas in theory won’t do much for you and your skills.
For even more practice, there are exercises called Challenges at the end of each chapter. These
exercises provide additional practice and will make you more confident of what you’ve just learned. I
strongly suggest you do as many of the Challenges as you can.
You will also see sections called For the More Curious at the end of some chapters. These are more
in-depth explanations of the topics covered in the chapter. They are not absolutely essential to get you
where you’re going, but I hope you’ll find them interesting and useful.
Big Nerd Ranch hosts a forum where readers discuss this book and the exercises in it. You can find it at
http://forums.bignerdranch.com/.
You will find this book and programming in general much more pleasant if you know how to touch-
type. Touch-typing, besides being much faster, enables you to look at your screen and book instead
of at the keyboard. This makes it much easier to catch your errors as they happen. It is a skill that will
serve you well for your entire career.
How the life of a programmer works
By starting this book, you’ve decided to become a programmer. You should know what you’ve signed
up for.
The life of a programmer is mostly a never-ending struggle. Solving problems in an always-changing
technical landscape means that programmers are always learning new things. In this case, “learning
new things” is a euphemism for “battling against our own ignorance.” Even if a programmer is working
with a familiar technology, sometimes the software we create is so complex that simply understanding
what’s going wrong can often take an entire day.
If you write code, you will struggle. Most professional programmers learn to struggle hour after hour,
day after day, without getting (too) frustrated. This is another skill that will serve you well. If you are
4
How the life of a programmer works
curious about the life of programmers and modern software projects, I highly recommend the book
Dreaming in Code by Scott Rosenberg.
Now it’s time to jump in and write your first program.
5
This page intentionally left blank
2
Your First Program
Now that we know how this book is organized, it’s time to see how programming for the Mac and for
iPhone and iPad works. To do that, you will
• install Apple’s Developer Tools
• create a simple project using those tools
• explore how these tools are used to make sure our project works
At the end of this chapter, you will have successfully written your first program for the Mac.
Installing Apple’s developer tools
To write applications for Mac OS X (the Macintosh) or iOS (the iPhone and iPad), you will be using
Apple’s developer tools. You can download these tools from http://developer.apple.com/ or
purchase them from the Mac App Store.
After you’ve installed the tools, find the /Developer folder at the root level of your hard drive. This
folder contains what you need to develop applications for Mac OS X desktops and iOS mobile devices.
Our work in this book is going to be conducted almost entirely with one application – Xcode, which
is found in the /Developer/Applications folder. (It is a good idea to drag the Xcode icon over to the
dock; you’ll be using it an awful lot.)
Getting started with Xcode
Xcode is Apple’s Integrated Development Environment. That means that everything you need to write,
build, and run new applications is in Xcode.
A note on terminology: anything that is executable on a computer we call a program. Some programs
have graphical user interfaces; we will call these applications.
Some programs have no graphical user interface and run for days in the background; we call these
daemons. Daemons sound scary, but they aren’t. You probably have about 60 daemons running on
your Mac right now. They are waiting around, hoping to be useful. For example, one of the daemons
running on your system is called pboard. When you do a copy and paste, the pboard daemon holds
onto the data that you are copying.
7
)""(
% ' '" ) & ) & ' ' U+
! * )+ + ' '' & )
'' + ) & ' ) &!
++G ' '' ) ) + + *!
B )+ ' ) && !* * & &
- !C) !, ' ' ) !
( ) ) )' & @'!K ) '
+ & ' )+ + ! & )' & '
!( & ' !
( )*"" %
# ) !
' ) + @!( ' & + G' & ) ;
*) )" )!K ) ) ! "# '!, '
$ )' ) ) )+ + ' !, '*)
* ;%&' "(' ! *!
/
Where do I start writing code?
Figure 2.2 Choose options
Press the Next button.
Now choose the folder in which your project directory will be created. You won’t need a repository for
version control, so you can uncheck that box. Finally, click the Create button.
You’ll be creating this same type of project for the next several chapters. In the future, I’ll just say,
“Create a new C Command Line Tool named program-name-here” to get you to follow this same
sequence.
(Why C? Remember, Objective-C is built on top of the C programming language. You’ll need to have
an understanding of parts of C before we can get to the particulars of Objective-C.)
Where do I start writing code?
After creating your project, you’ll be greeted by a window that shows how AGoodStart will be
produced.
9