Beginning Mac Programming Develop with Objective-C and Cocoa doc

417 273 0
Beginning Mac Programming Develop with Objective-C and Cocoa doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Beginning Mac Programming Develop with Objective-C and Cocoa Tim Isted The Pragmatic Bookshelf Raleigh, North Carolina Dallas, Texas Many of the designations used by manufacturers and sellers to distinguish their prod- ucts are claimed as t rademarks. 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 capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and t he 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 information (including program listings) 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, stored 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 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 A pplication . . . . . . . . . . . . . . . . . . . . . . . . . . 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 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 Mechanisms 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 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 breed 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 exterior lies a fascinating world. All computer plat- forms have communities of software developers, each equally devoted 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 r ewards. 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 reasonable excuse not to sit down and write softwar e 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 THE INTENDED AUDIENCE 11 putting them into practice in real-world situations, right from the start. Over the course of the book, you’ll learn enough that you can 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 co m- puter science. It’s intended to be read by people who’ve spent time working with the Mac, perhaps as power users of their applications, or at least people with the confidence that they know enough to explain the difference between, say, a menu and a window. Most importantly, the book is intended for people who have little or no previous program- ming knowledge. If you already r evel in the intricacies of hash tables or take pleasure in analyzing complex algorithms, this book probably isn’t for you. Simi- larly, if you prefer to learn theory first or you work best studying com- puter 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 program- ming skills, picking them up as they relate to the language we’re learn- ing and to the coding we’ll be doing. By the time you reach the end, not only will you have learned enough to start building your own Mac appli- cations, 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 pro- g ramming 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 language is much easier than learning to speak a foreign language; computers understand only a relatively limited vocabulary and grammar. For some of the programming principles we’ll be learning, we’ll intro- duce concepts using a kind of “pseudolanguage,” which is r eally just standard English made more formulaic. As will quickly become clear, this pseudolanguage isn’t too far from what Objective-C actually looks WHAT’S NEEDED? 12 like. Once we’ve learned to recognize the basic structure of a code project and learned the grammar, or syntax used inside the project files, it’s not too difficult to work out what’s going on in the code. At the same time that we’re learning Objective-C, we’ll be 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 the end of this book, we’ll even take a quick foray into writing iPhone software. The software-building processes we’ll learn throughout the book apply just as much on the iPhone as they 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 e ither 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. You won’t need to buy any special software. As we’ve already said, Apple’s developer tools are available either on the system discs that came with your computer (or on OS X upgrade discs) or for download from Apple’s Developer Connection website. You’ll need to register with Apple as a Developer Connection member to download the software, but registration is free. The developer tools must be installed—they probably won’t be available to run on your hard drive unless you’ve specifically installed them. In- stallation is very easy; for help, take a look at Appendix B, on page 403. T he only additional considerations are if you want to take iPhone coding further. As a start, the tools used to write for the iPhone OS require an Intel-based Mac. If you want to test and run your software on a real iPhone or iPod touch (rather than in a simulator on your desktop Mac), you’ll need to sign up as a registered iPhone Developer; this isn’t particularly expensive but, at the time of writing, bears an annual fee ACKNOWLEDGMENTS 13 of $99 for individuals. Rest assured that you won’t need to do this to get the most out of this book, though. The screenshots in this book are taken from version 3.2 of the developer tools—the version that comes with Mac OS X 10.6, Snow Leopard. If you’re running Mac OS X 10.5, Leopard, you may find that some parts of Xcode look slightly different, but it shouldn’t be too difficult to work out how your version relates to what you see in this book. 1.4 Acknowledgments Although it’s m y name that’s listed on the front, this book would not exist were it not for the work of a very large number of people. Thankfully, the ever-awesome publisher, Pragmatic Bookshelf, also in- cludes the name of the editor on the cover, which is truly fitting for what Colleen Toporek has put into this project. If I simply used the standard author phrase about “tireless support,” it would be one of the biggest understatements of all time. This has been a partnership from beginning to end, and this is as much her book as it is mine. I have also been lucky enough to have an incredible team of technical reviewers, reading through manuscripts at various stages. The early input from Lyndia Zarra, Bill Dudney, and Rob McGovern requires spe- cial mention, as it helped shape much of the book’s path and style; they even provided a second set of comments once the first draft was almost complete, for which I doubtless owe an as yet undisclosed number of drinks. My drawing skills are somewhat lacking, so I’m indebted to David Per- kins for his willingness to turn my horrendous scribbles into recog- nizable shapes. I am also extremely grateful to Dave Verwer, Chris Adamson, Dave Klein, and David Flagg for their support and technical comments on the book as a whole as it got closer to completion, and to Uli Kusterer, Danny Greg, Matt Gallagher, Loren Brichter, Cathy Shive, and Daniel Jalkut for looking over and commenting on the near-final manuscript. Finally, I’d like to thank all those who submitted errata and forum ques- tions on the book as it went 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! LET’S GO 14 1.5 Let’s Go Writing software for the Mac, and indeed programming in general, can be incredibly rewarding. It doesn’t necessarily have to be done at 3 a.m. fueled on coffee or cola, but sometimes it’s easy to get carried away knowing that some awesome feature is so close to working. We’ll probably manage to avoid some of the blood, sweat, and tears normally associated with learning programming, but even those who have suffered for their art will tell you that it’s worth it to use a great piece of software every day and be able to say “I made that!” And, of course, it’s even greater to watch other people using and loving (and maybe paying for ) your software too. So, let’s get started! [...]... the Mac OS X heading), and you’ll see several types of project templates listed in the upper-right half of the window A standard Mac application can be one of two fundamental project types Cocoa Application and Cocoa Document-based Application The difference between these two is perhaps best explained with examples Apple’s Pages and Microsoft’s Word are examples of document-based applications iTunes and. .. bits of useful output, and modifying it to test various features of Mac software development as you learn them The next chapter introduces a few basic programming principles, and we’ll actually get to start coding Feel free to experiment with the various objects, palettes, and features provided by Interface Builder, but make sure that you have a clean copy of TextApp to work with for the next chapter... to user input, and how they change the underlying data In Mac applications, this code is written inside objects 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 Objective- C and Cocoa, you will be working almost entirely with objects If “working with objects” sounds... let’s expand our example a little with some extra classes: a PropertyDeveloper class, a Builder class, and a CityOfficial class These objects need to be able to communicate with each other; for example, the developer needs to know when a house is finished so the city official can be sent there Let’s look at the class description for the PropertyDeveloper class as an example: • Class name: PropertyDeveloper... into the fantastic world of building Mac OS X applications using Apple’s Cocoa framework Despite not actually writing a single line of code, we’ve made a reasonably functional application with some impressive text-editing functionality just by working with the resources inside a Cocoa application This is all well and good, but to produce applications that are useful and functional in the real world (notice... general house blueprint describes the floor plans and measurements, and so on Each house built from the blueprint has two assignable values: the door color and the house address In programming terms, the blueprint has a large amount of fixed functionality 34 A N I NTRODUCTION TO O BJECTS and data, such as describing the house foundations, walls, and roof, along with the two changeable attributes We might... like the New and Open commands grayed out The Edit menu contains the standard pasteboard actions such as Copy and Paste The Window menu contains commands that affect the blank window visible on screen You can minimize it to the Dock or zoom it to fill your screen One of the most important principles of building software for the Mac platform is that applications should follow a standard set of interface... When it receives this message, the developer does the following: houseHasBeenBuilt { find friendly city official tell city official to 'approveHouseAndAssignAddress' } The city official approves the house, assigns an address, then calls the developer object back with the message houseHasBeenApprovedWithAnAddress, at which point the developer does this: houseHasBeenApprovedWithAnAddress { set address of... to “reinvent the wheel.” When writing Mac software, we use the Cocoa framework, provided for us by Apple 22 A PPLICATION R ESOURCES You might recall that when we created our TextApp project, we chose the Cocoa Application template By creating an application using Cocoa, we’re relieved from worrying about the basic functionality exhibited by most Mac applications, and left to worry about writing code... differently-colored circles for Close, Minimize, and Zoom 9 Draw the window’s title in the center of the bar 10 Fill out the rest of the window with its content 11 Wait for the user to do something 31 A N I NTRODUCTION TO O BJECTS We can break this list down into three sections The first section covers drawing the menu bar and menus, the second deals with the window and its content, and the final section addresses waiting . Beginning Mac Programming Develop with Objective-C and Cocoa Tim Isted The Pragmatic Bookshelf Raleigh,. upper-right half of the window. A standard Mac application can be one of two fundamental project types Cocoa Application and Cocoa Document-based Application.

Ngày đăng: 22/03/2014, 15:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan