Prepared exclusively for James Carlson What Readers Are Saying About Beginning Mac Programming Helping a complete novice get of f the ground building real Mac (and iPhone) apps is daunting—I would have thought impossible—but Tim makes some of the toughest concepts of Cocoa accessible and enjoyable. I get tons of email from people looking to get into Cocoa programming who don’t know where to start, and there really hasn’t been a good resource to point them to until this book. Loren Brichter Owner, atebits LLC Perfect for anyone who is new to Objective-C. It is laid out well, and the examples let you jump right in to developing an application. This will be a well-thumbed reference for me for quite some time. David Flagg Internet Technology Specialist, National Science Foundation Isted’s book gently places you on the path, giving you the guided tour not just of Mac programming but of programming itself. Simple, evocative examples take care of reinforcing the theory he deftly slips into the conversation. If you want to get into Mac programming quickly, at your own pace, this is your book. Uli Kusterer Software Engineer, The Void Software A gentle, practical, and comprehensive introduction to Mac development, which is genuinely suitable for people who have never programmed before. It will not only have you building applications but also understanding how they work. Dave Verwer Director, Shiny Development Ltd. Prepared exclusively for James Carlson If you are new to programming and want to write the next killer app, this is a great place to start. Tim takes you from the very basics of programming to some fairly advanced stuff, all the while never forgetting that you are new to this. The book is filled with great explanations of not only how to do stuf f but also why you should do them. I highly recommend this book to people who are new to programming. Especially if you want to build an iPhone application but have never programmed before, this book will take you through a great introduction to programming in general and leave you ready to tackle the iPhone SDK. Bill Dudney Owner, Gale Factory Software LLC This book is recommended for anyone starting out with no prior experience with programming or Cocoa development. By introducing fundamental programming principles side by side with a fantastic introduction to the Cocoa frameworks and their tools, Tim gives aspiring developers a foundation on which they can realize their goal of creating software for any modern Apple platform. Cathy Shive Senior Developer, Sofa B.V. Tim Isted clearly remembers what it was like when he first learned Objective-C, and it shows. He understands when things will be confusing and when you will be excited you got it all to work. Lyndia Zarra Owner, LIZography A book like this is all too rare to find when it comes to beginning programming literature. It focuses on results right fr om the get-go and has you building applications from the very start, a great way to monitor your progress. All the while it manages to teach you fundamental programming techniques in a clear, concise manner, while not sounding patronizing. An absolute must for anyone considering taking up programming on the Mac platform. Danny Greg Cocoa Developer, Realmac Software Prepared exclusively for James Carlson This book is great; it thankfully eschews the “traditional” dry format of teaching programming and takes you on a journey that will leave you itching to get on and write your own programs. Robert McGovern I’ve always been a fan of learning programming by boldly diving in. This book is a prime example of that idea: you create your first program in the second chapter, and create your first objects and code in the third. The traditional fundamentals of programming are there in the middle of the book, and an introduction to Mac application design fills out the end. But I challenge you to be bold. Play with everything, make your own marks, and this book will serve you well on the path to becoming a great Mac programmer. Matt Gallagher Sole Proprietor, ProjectsWithLove An extremely gentle introduction to the fundamentals of developing for the Mac. While some beginner books presume knowledge of arcane tidbits, this author has plotted a careful course that starts with a few essentials and then builds upon them bit by bit. Daniel Jalkut Founder, Red Sweater Software Before Isted’s book, learning how to program and learning how to program Cocoa were sadly two distinct undertakings. The best introductory programming books didn’t target Cocoa, and the Cocoa books presumed knowledge of programming. Tackling two separate books wasn’t an impossible task for a new programmer, but it was a speed bump along an already steep grade. In this book, Isted offers a seamless, gentle slope towards reaching Mac programming heights. I’m happy I can now recommend Isted’s book to those who ask me how they can start programming Apple’s lovely machines. I’m happy I can now recommend Isted’s book to those who ask me how they can start programming Apple’s lovely machines. Jonathan “Wolf” Rentzsch President, Red Shed Software Company Prepared exclusively for James Carlson Beginning Mac Programming Develop with Objective-C and Cocoa Tim Isted The Pragmatic Bookshelf Raleigh, North Carolina Dallas, Texas Prepared exclusively for James Carlson Many of the designations used by manufacturers and sellers to distinguish t heir prod- ucts are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capit al letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of infor mat ion (including program li stings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://www.pragprog.com Copyright © 2010 Tim Isted. All rights reserved. No part of this publication may be reproduced, stor ed in a retrieval system, or transmit- ted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-10: 1-934356-51-4 ISBN-13: 978-1-934356-51-7 Printed on acid-free paper. P1.0 printing, March 2010 Version: 2010-3-3 Prepared exclusively for James Carlson Contents 1 Introduction 10 1.1 The Intended Audience . . . . . . . . . . . . . . . . . . . 11 1.2 What’s Involved? . . . . . . . . . . . . . . . . . . . . . . 11 1.3 What’s Needed? . . . . . . . . . . . . . . . . . . . . . . . 12 1.4 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . 13 1.5 Let’s Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2 Your First Application 15 2.1 Introducing Xcode . . . . . . . . . . . . . . . . . . . . . 15 2.2 The Main Event . . . . . . . . . . . . . . . . . . . . . . . 18 2.3 The Cocoa Framework . . . . . . . . . . . . . . . . . . . 22 2.4 Application Resources . . . . . . . . . . . . . . . . . . . 23 2.5 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 29 3 All About Objects 30 3.1 The Application Construction Process . . . . . . . . . . 30 3.2 An Introduction to Objects . . . . . . . . . . . . . . . . . 31 3.3 Object Inheritance . . . . . . . . . . . . . . . . . . . . . 38 3.4 Writing Code for Our Own Objects . . . . . . . . . . . . 40 3.5 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 55 4 Object Messaging 56 4.1 Defining a New Method . . . . . . . . . . . . . . . . . . . 56 4.2 The Target-Action Mechanism . . . . . . . . . . . . . . . 59 4.3 Sending Messages from Our Code . . . . . . . . . . . . 64 4.4 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 73 5 Variables and Memory 74 5.1 How Memory Works . . . . . . . . . . . . . . . . . . . . . 74 5.2 Using Variables . . . . . . . . . . . . . . . . . . . . . . . 79 5.3 The Scope of a Variable . . . . . . . . . . . . . . . . . . . 88 5.4 Memory Addressing . . . . . . . . . . . . . . . . . . . . . 90 5.5 Pointers Again . . . . . . . . . . . . . . . . . . . . . . . . 94 5.6 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 96 Prepared exclusively for James Carlson CONTENTS 8 6 Passing Information Around 97 6.1 Returning Values . . . . . . . . . . . . . . . . . . . . . . 97 6.2 Methods and Arguments . . . . . . . . . . . . . . . . . . 105 6.3 Class Methods . . . . . . . . . . . . . . . . . . . . . . . . 111 6.4 Passing Values by Reference . . . . . . . . . . . . . . . . 115 6.5 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 117 7 Objects and Memory Management 119 7.1 Memory Considerations . . . . . . . . . . . . . . . . . . 119 7.2 Allocating Memory for Objects . . . . . . . . . . . . . . . 121 7.3 Creating Objects in Code . . . . . . . . . . . . . . . . . . 124 7.4 The Object Life Cycle . . . . . . . . . . . . . . . . . . . . 129 7.5 Denying Responsibility . . . . . . . . . . . . . . . . . . . 133 7.6 Initializing with Arguments . . . . . . . . . . . . . . . . 137 7.7 Utility Class Methods . . . . . . . . . . . . . . . . . . . . 140 7.8 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 144 8 Collecting Information 145 8.1 Introducing Arrays . . . . . . . . . . . . . . . . . . . . . 145 8.2 Using Arrays in an Application . . . . . . . . . . . . . . 148 8.3 Object Mutability . . . . . . . . . . . . . . . . . . . . . . 154 8.4 A New Application . . . . . . . . . . . . . . . . . . . . . . 160 8.5 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 181 9 Branching Out 183 9.1 Introducing if and else . . . . . . . . . . . . . . . . . . . 183 9.2 All About the Truth . . . . . . . . . . . . . . . . . . . . . 199 9.3 Stylistic Conventions . . . . . . . . . . . . . . . . . . . . 202 9.4 Switching Around . . . . . . . . . . . . . . . . . . . . . . 205 9.5 Writing Init Methods . . . . . . . . . . . . . . . . . . . . 208 9.6 Adding Conditional Statements to the Shopping List Application . . . . . . . . . . . . . . . . . . . . . . . . . . 210 9.7 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 217 10 Looping and Enumerating 218 10.1 Introducing Array Enumeration . . . . . . . . . . . . . . 218 10.2 Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 10.3 Traditional for Loops . . . . . . . . . . . . . . . . . . . . 224 10.4 Enumerating an Array with a Traditional for Loop . . . 228 10.5 Other Types of Loop . . . . . . . . . . . . . . . . . . . . 231 10.6 A Simple Change to Our Shopping List Application . . 234 10.7 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 236 Report erratum this copy is (P1.0 printing, March 2010) Prepared exclusively for James Carlson CONTENTS 9 11 Objects, Encapsulation, and MVC 238 11.1 The Main Types of Object . . . . . . . . . . . . . . . . . 238 11.2 Designing Model Objects . . . . . . . . . . . . . . . . . . 241 11.3 Reworking the Shopping List Application . . . . . . . . 251 11.4 Creating a Shopping List Item Object . . . . . . . . . . 262 11.5 Reworking the Shopping List Application Again . . . 269 11.6 Introducing Objective-C 2.0 Properties . . . . . . . . . . 271 11.7 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 277 12 All About Views 278 12.1 Simple Geometry in Two Dimensions . . . . . . . . . . 278 12.2 Working with Windows and Views . . . . . . . . . . . . 282 12.3 The View Hierarchy . . . . . . . . . . . . . . . . . . . . . 290 12.4 Custom Views . . . . . . . . . . . . . . . . . . . . . . . . 295 12.5 Back to the Shopping List Application . . . . . . . . . . 306 12.6 Views and Cells . . . . . . . . . . . . . . . . . . . . . . . 310 12.7 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 318 13 Mac OS X and Cocoa Mechanis ms 320 13.1 Delegation . . . . . . . . . . . . . . . . . . . . . . . . . . 321 13.2 Notifications . . . . . . . . . . . . . . . . . . . . . . . . . 337 13.3 Working with Events . . . . . . . . . . . . . . . . . . . . 347 13.4 Responders and the Responder Chain . . . . . . . . . . 359 13.5 Archiving with NSCoding . . . . . . . . . . . . . . . . . . 367 13.6 Chapter Summary . . . . . . . . . . . . . . . . . . . . . 374 14 Where to Go from Here 376 14.1 Important Technologies . . . . . . . . . . . . . . . . . . 377 14.2 Finding Information . . . . . . . . . . . . . . . . . . . . 382 14.3 Book Summary . . . . . . . . . . . . . . . . . . . . . . . 386 A Developing for the iPhone OS 387 B Installing Xcode 403 C Bibliography 408 Index 409 Report erratum this copy is (P1.0 printing, March 2010) Prepared exclusively for James Carlson Chapter 1 Introduction The iPad, the iPhone, the iPod, the iMac The world according to Apple is vast and ever-expanding. The Mac and iPhone OS platforms seem to bre ed passionate users, united in their love for software and hardware that looks beautiful, behaves exactly how they expect, and works without the pains of hardware incompati- bilities, driver installations, and convoluted interfaces. Behind this alluring ex terior lies a fascinating world. All computer plat- forms have communities of software developers, each equally dev oted to what they do. What seems to set the Mac platform apart, though, is that so much of the available Mac and iPhone software has been written either by individual developers, working as independents, or for relatively small companies that maintain that “indie” feel. The sense of community is great, newcomers are welcomed and respected, and the indie-developer experience offers many rewards. What also sets the Mac apart from another, reasonably well-known computer platform, is that the tools to write software come bundled free of charge with every Mac. They’re even available as free downloads from Apple’s website if you happen not to be able to find the original system discs or want the absolutely latest version. Perhaps the only reas onable excuse not to sit down and write software right away is that the learning curve feels steep. The advice is often to “Go away and learn C, and come back when you’re done!” The aim of this book is to offer a different path. We’ll be jumping headfirst into creating applications on the Mac that look and behave like the other Mac applications you’re used to. We’ll certainly be learning general programming principles, but we will be Prepared exclusively for James Carlson [...]... do the Mac desktop, so we’ll be learning skills that open up multiple new worlds of creativity! 1.3 What’s Needed? If you’re reading this book, it’s probably fairly likely that you either own or have access to a Mac It doesn’t matter whether it’s an old PowerPC-based model or the latest top-of-the-line, Intel-based Mac Pro As long as it runs OS X, you can use it with this book to learn Mac programming. .. building your own Mac applications, but you’ll be confident enough to take on the more advanced literature that’s available 1.2 What’s Involved? So, what will we cover in this book? Well, we’ll be learning a programming language On the Mac, this means learning something called Objective-C Don’t worry, it’s not too scary, and we won’t be trying to learn all of it, all at once Learning a computer programming. .. started! Report erratum Prepared exclusively for James Carlson this copy is (P1.0 printing, March 2010) 14 Chapter 2 Your First Application Welcome to the world of Mac programming! Many programming books begin by giving you long histories of programming languages, introducing a lot of very abstract ideas before you actually get to do anything Even when you’re eventually allowed to do something at your... through the Pragmatic Beta process The Mac and iPhone developer community has to be one of the friendliest, most helpful and supportive groups in existence We look forward to welcoming you, the reader, into it! Report erratum Prepared exclusively for James Carlson this copy is (P1.0 printing, March 2010) 13 L ET ’ S G O 1.5 Let’s Go Writing software for the Mac, and indeed programming in general, can be incredibly... fend for yourself, with enough knowledge of how the Mac programming world works that you know where to go to fill gaps in your knowledge with information from the right sources 1.1 The Intended Audience This book is designed for those of us who don’t have a degree in computer science It’s intended to be read by people who’ve spent time working with the Mac, perhaps as power users of their applications,... subsequent chapters of this book, we’ll use this simple application to demonstrate how to write code Our aim is therefore not only to learn a new programming “language” but to learn how software is built from a Mac perspective, using this language inside a real Mac application, which we’ll create using Apple’s developer tools 2.1 Introducing Xcode If you’ve done any coding at all on other platforms or... how they respond to user input, and how they change the underlying data In Mac applications, this code is written inside objects Prepared exclusively for James Carlson A N I NTRODUCTION TO O BJECTS 3.2 An Introduction to Objects You have probably heard the phrase object-oriented programming (or OOP) When writing software for the Mac or the iPhone using ObjectiveC and Cocoa, you will be working almost... learning about a framework provided by Apple, called Cocoa, and, obviously, we’ll be spending a lot of time using the developer tools Xcode and Interface Builder to make Mac software The great thing about learning Objective-C for the Mac desktop is that it is also the language used to write software for the iPhone OS, that is, for applications that run on Apple’s iPhone and iPod touch devices; toward... previous programming knowledge If you already revel in the intricacies of hash tables or take pleasure in analyzing complex algorithms, this book probably isn’t for you Similarly, if you prefer to learn theory first or you work best studying computer stuff away from your computer, it’s probably wise to look at some of the other books out there Throughout the course of this book, we’ll be going over basic programming. .. is different We’re going to begin our journey together by creating a simple but fully functional application that exhibits all the wonderful characteristics of a typical Mac application Our application will launch like any normal Mac app, display its own window, show its own menu bar, respond to all sorts of user input, and, astonishingly, even allow the user to print to a connected printer All of . tour not just of Mac programming but of programming itself. Simple, evocative examples take care of reinforcing the theory he deftly slips into the conversation. If you want to get into Mac programming quickly,. how they can start programming Apple’s lovely machines. Jonathan “Wolf” Rentzsch President, Red Shed Software Company Prepared exclusively for James Carlson Beginning Mac Programming Develop. gentle slope towards reaching Mac programming heights. I’m happy I can now recommend Isted’s book to those who ask me how they can start programming Apple’s lovely machines. I’m happy I can now