c1.jpg beginning mac os x...

30
Beginning Mac OS ® X Programming Michael Trent and Drew McCormack

Upload: phamkhanh

Post on 22-Apr-2018

218 views

Category:

Documents


2 download

TRANSCRIPT

  • Beginning Mac OS X Programming

    Michael Trent and Drew McCormack

    01_573993 ffirs.qxd 6/16/05 2:18 PM Page i

    C1.jpg

  • 01_573993 ffirs.qxd 6/16/05 2:18 PM Page iv

  • Beginning Mac OS X Programming

    Michael Trent and Drew McCormack

    01_573993 ffirs.qxd 6/16/05 2:18 PM Page i

  • Beginning Mac OS X Programming

    Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright 2005 by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in Canada

    ISBN-10: 0-7645-7399-3

    ISBN-13: 978-0-7645-7399-6

    Manufactured in the United States of America

    10 9 8 7 6 5 4 3 2 1

    1B/QX/QX/QV/IN

    Library of Congress Cataloging-in-Publication DataTrent, Michael, 1972-

    Beginning Mac OS X programming / Michael Trent and Drew McCormack.p. cm.

    Includes index.ISBN-13: 978-0-7645-7399-6 (paper/website)ISBN-10: 0-7645-7399-3 (paper/website)

    1. Mac OS. 2. Operating systems (Computers) 3. Macintosh(Computers)Programming. I. McCormack, Drew, 1971- II. Title.

    QA76.76.063T74565 2005005.4'46dc22

    2005010351

    No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by anymeans, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, orauthorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 RosewoodDrive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should beaddressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317)572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

    LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REP-RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON-TENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUTLIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATEDOR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINEDHEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTAND-ING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PRO-FESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENTPROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BELIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE ISREFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMA-TION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THEORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READ-ERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED ORDISAPPEARED BETWEEN THEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

    For general information on our other products and services please contact our Customer Care Department withinthe United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

    Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress aretrademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and othercountries, and may not be used without written permission. Mac OS is a registered trademark of Apple Computer,Inc. in the U.S. and other countries. All other trademarks are the property of their respective owners. Wiley Publish-ing, Inc., is not associated with any product or vendor mentioned in this book.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not beavailable in electronic books.

    01_573993 ffirs.qxd 6/16/05 2:18 PM Page ii

    www.wiley.com

  • About the AuthorsMichael Trent has been programming in Objective-C since1997 and programming Macs since wellbefore that. He is a regular contributor to Steven Franks www.cocoadev.com website, technicalreviewer for numerous books and magazine articles, and occasional dabbler in Mac OS X open sourceprojects. Currently, he is using Objective-C and Apple Computers Cocoa frameworks to build profes-sional and consumer applications for Mac OS X. Michael holds a Bachelor of Science in ComputerScience and a Bachelor of Arts in Music from Beloit College of Beloit, Wisconsin. He lives in Pittsburgh,Pennsylvania, with his family.

    Drew McCormack has a Ph.D. in Chemical Physics and works as a computational scientist in theTheoretical Chemistry group at the Free University in Amsterdam. He is involved in developing theQuantum Chemistry software ADF (www.scm.com), which is run the world over on computers rangingfrom desktop Macs to massive supercomputers. He programs regularly in Python, C++, Objective-C,Fortran, and Bash, and in his spare time develops the Cocoa financial software Trade Strategist (www.trade-strategist.com). Drew maintains the Maniacal Extent websitea reference to the chaoticdimension, timewhich details his various interests and activities (www.maniacalextent.com).

    CreditsAcquisitions EditorKatie Mohr

    Senior Development EditorJodi Jensen

    Technical EditorTerrence Talbot

    Production EditorFelicia Robinson

    Copy EditorKim Cofer

    Editorial ManagerMary Beth Wakefield

    Vice President & Executive Group PublisherRichard Swadley

    Vice President and PublisherJoseph B. Wikert

    Project CoordinatorErin Smith

    Graphics and Production SpecialistsApril FarlingCarrie FosterLauren GoddardDenny HagerJoyce HaugheyAmanda SpagnuoloJulie Trippetti

    Quality Control TechniciansLeeann HarneyJessica KramerJoseph NiesenCarl PierceDwight Ramsey

    Media Development SpecialistsAngela DennyKit MaloneTravis Silvers

    Proofreading and IndexingTECHBOOKS Production Services

    01_573993 ffirs.qxd 6/16/05 2:18 PM Page iii

  • 01_573993 ffirs.qxd 6/16/05 2:18 PM Page iv

  • For Angela and Katie MT

    For Jennifer and Gileesa DM

    01_573993 ffirs.qxd 6/16/05 2:18 PM Page v

  • 01_573993 ffirs.qxd 6/16/05 2:18 PM Page vi

  • Contents

    Acknowledgments xviiIntroduction xix

    Part I: Mac OS X Developer Resources 1

    Chapter 1: The Mac OS X Environment 3

    Introducing the Mac OS X 3Try It Out: Slide Master 4

    The Core Operating System 6The Kernel 8The System Library 8Unix Commands 9

    Try It Out: Experiencing Darwins Command-Line Interface 9

    Graphics and Media Layers 11The Quartz Compositor 12Quartz 2D 14OpenGL 14QuickTime 15

    Application Frameworks and UI 15Cocoa 16Carbon 16Java JDK 17

    Apple Human Interface Guidelines 18Summary 19Exercises 20

    Chapter 2: Developer Tools 21

    Installing the Developer Software 21Developer Applications 22

    Build Tools 22Performance Tools 22

    MallocDebug 23ObjectAlloc 24Quartz Debug 25Sampler 26

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page vii

  • viii

    Contents

    Shark 27Spin Control 28Thread Viewer 28

    Other Utilities 30FileMerge 31Icon Composer 31PackageMaker 31Pixie 33Property List Editor 33Script Editor 34

    Command-Line Tools 34cc / gcc 35diff 36gdb 36GetFileInfo / SetFile 37Rez / DeRez 37sample 38sh / bash / tcsh 38Top 39

    Developer Documentation and Examples 39Conceptual Documentation 40

    Apple Human Interface Guidelines 42Mac OS X Technology Overview 42Xcode 2.0 User Guide 42

    API Reference 42Examples 46Man Pages 47

    Apple Developer Connection 48Documentation 49Examples 51Mailing Lists 53Developer Tools 53Developer Support 54Business Resources 54

    Summary 54Exercises 55

    Chapter 3: Xcode 57

    Starting a New Project 58Try It Out: Create a Default Project 58

    Working with Files 61Try It Out: Using Xcodes Groups & Files Viewer 61

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page viii

  • ix

    Contents

    Writing Your Code 65Try It Out: Working in the Code Editor 65

    A Second Look at Indenting 70Try It Out: Indenting Automatically 70

    Building and Running 72Try It Out: Building Your Calculator Project 72

    Using the Debugger 78Try It Out: Debugging Changes to Calculator 78

    Online Documentation 84Try It Out: Searching the Online Documentation 84

    Summary 89Exercises 90

    Chapter 4: Interface Builder 93

    Starting a New Interface 93Try It Out: Create a New Interface 94

    Building Menus 97Try It Out: Building Carbon Menus 98

    A Second Look at Menus 103Try It Out: Building Cocoa Menus 103

    Building Windows 106Try It Out: Building a Dialog Window 106

    Making Windows Resizable 113Try It Out: Building a Resizable Cocoa Window 114

    A Second Look at Resizing Windows 120Try It Out: Building a Resizable Carbon Window 120

    Summary 123Exercises 124

    Part II: Application Programming 125

    Chapter 5: The Application 127

    Basic Bundle Structure 127Opaque Directory 128Versioned Bundles 128The Info.plist File 130Executable Code 131Global Resources 131Localized Resources 131

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page ix

  • x

    Contents

    Examining Application Bundles 132Try It Out: Examining the Mail Application 132

    Building an Application Bundle 136Try It Out: Building the Slide Master Bundle 137

    Application Preferences 144Try It Out: Examining Preference Files 144

    Summary 150Exercises 151

    Chapter 6: The C Language 153

    A Little History 153Getting Started 154

    Try It Out: Compiling and Running a C Program with Xcode 155

    Variables and Data Types 157Operators 159Arrays and Pointers 163

    Try It Out: Working with Pointers 166

    Conditional Branching 169Loops 173

    Try It Out: Statistical Analysis of Array Data 177

    Functions 180Characters and Strings 183Input/Output 186

    Try It Out: Searching a File 191

    Data Structures 194Memory Management 196The Preprocessor 200Organizing Programs 205

    Try It Out: Getting Started with MyAddressBook 207

    Try It Out: Writing the AddressBook ADT 210

    Try It Out : Finishing Off MyAddressBook 218

    Summary 224Exercises 225

    Chapter 7: The Objective-C Language 227

    Object-Oriented Programming 227Classes and Objects 229Methods 231

    Try It Out: Rewriting Grepper in Objective-C 233

    Data Hiding 237

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page x

  • xi

    Contents

    Subclassing 238Messaging 241Protocols and Informal Protocols 242Naming Conventions 246Creating and Destroying Objects 247Memory Management 250

    Try It Out: Memory Management with Cats 251

    Accessor Methods 253Try It Out: Beginning MyAddressBook in Objective-C 257

    Try It Out: Writing the AddressBook Class 260

    Try It Out: Writing the Controller and Command Classes 266

    Try It Out: Adding Command Subclasses 275

    Summary 278Exercises 278

    Chapter 8: Using the Cocoa Frameworks 279

    Connecting Cocoa Interfaces 280Connecting Interfaces Manually with Outlets and Actions 280

    Try It Out: Building the Email Formatter Interface 282

    Try It Out: Setting the Key View Loop 284

    Try It Out: Declaring a Custom Controller 287

    Try It Out: Connecting Controls to Your Controller 290

    Try It Out: Writing Your Controller 293

    Working with Cocoa Bindings 296Try It Out: Building the Email Formatter 2 Interface 297

    Try It Out: Creating an NSObjectController 297

    Try It Out: Connecting Controls to NSObjectController 298

    Try It Out: Writing Your EmailAddress Class 302

    The Model/View/Controller Design Pattern 305Working with Documents 306

    Creating a New Document 306Try It Out: Configuring a Scrollable Image View 308

    Try It Out: Setting the Nib Files Owner 310

    Try It Out: Writing a Custom NSDocument Subclass 311

    Try It Out: Writing a Custom NSWindowController Subclass 315

    Replacing the Existing MyDocument Class 318Try It Out: Replacing the MyDocument Class 318

    Subclassing Controls in Interface Builder 320Try It Out: Creating a Custom NSImageView Subclass 320

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page xi

  • xii

    Contents

    Connecting Menus 322Try It Out:Connecting Menus to the First Responder 323

    Try It Out: Implementing an Application Delegate 325

    Try It Out: Receiving Menu Commands in a Document 326

    Selecting Files with Open Panels 328Try It Out: Building a Simple Model Object 328

    Try It Out: Using Mutable Arrays 330

    Try It Out:Running an Open Panel 334

    Try It Out:Creating a New Document 336

    Tracking Changes with Notifications 339Try It Out: Sending and Receiving Notifications 340

    Using Drawers 343Try It Out: Adding a Drawer 344

    Working with Table Views 346Try It Out: Configuring Table Views in Interface Builder 346

    Try It Out: Defining a Table Data Source 349

    Handling Undo 354Try It Out: Handling Undo and Redo 354

    Archiving Objective-C Objects 356Try It Out: Archiving Objects 356

    Application Preferences 359Try It Out: Creating a Preference Window Interface 360

    Try It Out: Running the Modal Preferences Window 362

    Responding to Keyboard Events 368Try It Out: Responding to Keyboard Events 368

    Summary 370Exercises 371

    Chapter 9: Using the Carbon Frameworks 373

    Memory Management in Carbon 375Carbon Memory Functions 375

    Carbon Pointers 375Carbon Handles 375

    CoreFoundation Memory Conventions 377Connecting Carbon Interfaces 377

    Try It Out: Building the Carbon Email Formatter Interface 378

    Try It Out: Responding to Carbon Events 382

    Try It Out: Working with Carbon Controls 387

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page xii

  • xiii

    Contents

    Carbon File Manager 392FSSpec and FSRef 392Aliases 393

    Try It Out: Storing and Resolving Aliases 394

    Working with QuickTime 400Try It Out: Drawing into a GWorld 401

    Try It Out: Creating a New QuickTime Movie 404

    Try It Out: Creating a New Video Track 409

    Try It Out: Inserting New Video Samples 412

    Try It Out: Hooking Up the Movie Command 417

    Summary 421Exercises 421

    Part III: Script Programming 423

    Chapter 10: Overview of Scripting Languages 425

    What Is a Script? 425What Is a Scripting Language? 426Bash 427

    Why Bash? 427Try It Out: A Bash Example 428

    More Information 431AppleScript 432

    Why AppleScript? 432Try It Out: An AppleScript Example 432

    More Information 436Python 436

    Why Python? 437Try It Out: A Python Example 438

    More Information 445Perl 446

    Why Perl? 446Try It Out: A Perl Example 447

    More Information 451JavaScript and Dashboard 451

    Dashboard 452Try It Out: Beginning the DashBall Dashboard Widget 453

    Try It Out: Finishing the DashBall Dashboard Widget 459

    More Information 465

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page xiii

  • xiv

    Contents

    Other Scripting Languages 466Summary 466Exercises 467

    Chapter 11: The Bash Shell 469

    Getting Started 469The Command-Line Interface 470Interactive versus Script 470The Terminal Application 470Editors 471Configuring Bash 473

    Try It Out: Configuring Your Bash Shell 474

    Unix Basics 476Paths 476Locating and Learning Commands 478Running Commands and Other Executables 480Redirecting Input and Output 481

    Try It Out: Determining Your Memory by Redirecting Data 484

    Navigating the File System 486Working with Files and Directories 488File Permissions 491Globbing 494

    Try It Out : Interacting with the File System 496

    Searching for Files 497Working with Text 500

    Try It Out : Editing an HTML File with sed 504

    Process Control 505Mac OS X Exclusive Commands 507Overview of Other Commands 508

    Shell Programming 509Scripts 509Variables 510Quoting 513Conditional Branching 515Looping 518Functions 520

    Try It Out: Writing a Shell Script to Compress Large Files 521

    Summary 524Exercises 524

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page xiv

  • xv

    Contents

    Chapter 12: AppleScript and AppleScript Studio 527

    AppleScript 528Creating an AppleScript 528

    Try It Out: Using Script Editor 529

    Scriptable and Recordable Applications 530Apple Events 530Variables and Data Types 531

    Try It Out: Working with Data 535

    Handlers 537Control Statements 540

    Conditional Branching 540Looping 541tell 543

    Try It Out: Downloading and Saving Stock Quotes 546

    Operators 549Equality and Inequality Operators 550The Concatenation Operator 551The Contains Operator 552

    Specifying Elements 553Scripts and Objects 555Classes 558Working with Scripts 558

    Try It Out: Creating the User Interface for Slideshow Maker 559

    Try It Out: Finishing Off Slideshow Maker 562

    AppleScript Studio 568The AppleScriptCocoa Bridge 568Using Xcode 570Using Interface Builder 572

    Try It Out: Creating the Piles of Pictures User Interface 575

    Try It Out: Writing the Piles of Pictures Script 578

    Summary 586Exercises 587

    Chapter 13: Using Scripts Within Applications 589

    Running Subprocesses with C Functions 589Using the system Function 590Using popen to Run Scripts Asynchronously 594

    Try It Out: Creating a Cocoa Interface for Searcher 595

    Try It Out: Writing the Search Engine for Searcher 601

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page xv

  • xvi

    Contents

    Running Scripts with Cocoa 604Introducing NSTask 604Transferring Data with Pipes 605

    Try It Out: Creating a User Interface for Crumbs 607

    Try It Out: Finishing Off the Crumbs Application 612

    Summary 619Exercise 619

    Appendix A: Exercise Answers 621

    Appendix B: Developer Resources 659

    Appendix C: Developer Tools Roadmap 663

    Index 673

    02_573993 ftoc.qxd 6/16/05 2:20 PM Page xvi

  • Acknowledgments

    I would like to thank Steve Kochan for his help with this project early on. Thanks also to Brett Halle andPete Steinauer for their encouragement. Most of all, I would like to thank my wife, Angela, and mydaughter, Katie, for putting up with all the late nights. Michael Trent

    I wish to thank my wife, Jennifer, and daughter, Gileesa, for suffering my wacky schemes; my brotherCody McCormack, for being my mentor; and Pier Philipsen for being my sounding board in all matterstechnical. Drew McCormack

    03_573993 flast.qxd 6/16/05 2:21 PM Page xvii

  • 03_573993 flast.qxd 6/16/05 2:21 PM Page xviii

  • Introduction

    Mac OS X represents the union of many different operating system technologies. At its core you will findUnix, an operating system once reserved for high-end servers and workstations, now found on commondesktop systems. With Unix comes a whole history of tools, computer languages, and runtime environ-ments. At a higher level, you will find Carbon, a library made from elements of the original Macintoshoperating system. Although it is no longer responsible for managing the hardware itself, the Mac OS APIremains, providing special services unique to the Macintosh. Mac OS X also includes Cocoa, derivedfrom the application toolkits found on NeXTSTEP and OpenStep a result of Apples merger with NeXTin 1997. Other technologies have found their way into Mac OS X through the open source community,and Apple is hard at work developing new technologies unique to Mac OS X.

    Although the operating system is composed of all these separate pieces, Mac OS X still looks and feelslike a single piece of software. The Macintoshs legendary user interface still shines brightly today, pro-viding a consistent look and feel for the applications on your system. When you sit down to use yourcomputer, it just works for you. And aside from a few cosmetic differences, say using a command-lineinterface or a graphical interface, rarely are you aware of the differences between all these operating system technologies.

    Under the covers there are fundamental differences between these operating system technologies. Forexample, Carbon still provides its own special memory data types, and Cocoa requires its own object-oriented runtime. But there are no firm boundaries between these technologies; Cocoa can call CarbonAPI and vice versa. And though these technologies have their own history, strengths, and weaknesses,they are all still part of the same Mac OS X operating system.

    Who This Book Is ForThis book is for anyone who wants to get started writing programs that run on Mac OS X. Every Mac OS X system comes with everything you need: a complete set of development tools and resources. Butfinding the place to start can be challenging. This book provides a great starting point for programmingon Mac OS X and shows you how to find more information on your own.

    This book will appeal most to the hobbyist programmer who already has some exposure to a program-ming language. Experience with C or Objective-C, although helpful, is not required. You can learn thebasics of these languages, as well as concepts like object-oriented programming, as you go.

    If you are an experienced programmer familiar with one aspect of Mac OS X programming (such as shellscripting or Carbon), you can use this book to explore other aspects of Mac OS X programming. In addi-tion, you learn how to incorporate these new techniques into your existing programming style.

    03_573993 flast.qxd 6/16/05 2:21 PM Page xix

  • xx

    Introduction

    How This Book Is StructuredThis book takes a hands-on approach to learning the material using the Wrox Try It Out format. Afteryou learn about a particular element, you are presented with step-by-step instructions that walk youthrough using that element. You are encouraged to follow along on your own system by typing theexamples, running them, and if necessary debugging when they dont work quite right. A detailedexplanation of the example follows the step-by-step instructions under a How It Works heading.

    Some examples take the form of small stand-alone projects, designed to illustrate one particular conceptor technique. When appropriate, examples build on material presented in earlier chapters or examples,providing an opportunity to see the new material in a non-trivial context. Many of the examples focusedon Mac OS X application development build on an application called Slide Master, a functional image/slide show browser that you build piece by piece. Whenever possible, larger tasks have been brokendown into smaller examples to make them easier to digest.

    Each chapter includes a few exercises at the end, again illustrating the lessons presented earlier. You canwork through these examples on your own, at your own pace. Complete answers to each exercise areprovided in the appendix, so you can check your work or get a hint if you get stuck. Keep in mind thatin programming theres usually more than one way to do something; our solution isnt necessarily theonly correct solution.

    Chapters are collected into three broad categories, or parts: Mac OS X Developer Resources, ApplicationProgramming, and Script Programming. This keeps related material together and helps with the flow ofinformation from topic to topic. You are encouraged to cover the material in order so that you dont missanything. But if you want to skip ahead to learn about a specific topic, make a point of coming back tothe earlier material at a later time.

    Heres a brief summary of what youll find in each chapter:

    In Chapter 1, The Mac OS X Environment, you learn about Mac OS Xs system architecture. You alsoget a little hands-on experience using Mac OS Xs built-in command-line interface.

    In Chapter 2, Developer Tools, you find out about the resources that come with your copy of Mac OS X.You also learn how to find current versions of these resources on the Internet.

    In Chapter 3, Xcode, you explore the application used to build Mac OS X programs. A few simpleexamples introduce you to writing source code, building a finished product, and debugging programsone line of code at a time.

    Chapter 4, Interface Builder, walks you through the process of designing a graphic user interface onMac OS X. Examples in this chapter illustrate useful techniques for building an interface that conformsto Apples guidelines.

    In Chapter 5, The Application, you pick apart the individual elements that make up an application on Mac OS X. You learn how application resources are stored and how applications work in multiplelanguages.

    Chapter 6, The C Language, offers a brief introduction to the C programming language. If you are newto C, you will want to read this chapter before continuing on to Chapters 7, 8, or 9. In addition to learninghow to write programs in C, you learn how non-trivial C programs are divided among several source files.

    03_573993 flast.qxd 6/16/05 2:21 PM Page xx

  • xxi

    Introduction

    Chapter 7, The Objective-C Language, builds on Chapter 6 to teach you about Objective-C, the object-oriented language used by the Cocoa application frameworks.

    In Chapter 8, Using the Cocoa Frameworks, you discover how to write your own Cocoa applications,from designing a user interface, to writing the final code. The Cocoa application frameworks do a lot ofwork for you, freeing you up to concentrate on the unique aspects of your own application.

    Chapter 9, Using the Carbon Frameworks, explores how to build user interfaces with Carbon and howto use Carbon interfaces, such as QuickTime, from within Cocoa programs.

    In Chapter 10, Overview of Scripting Languages, you examine scripting languages available on the MacOS X system. Many of these languages extend Mac OS Xs command-line interface in one way or another.You get a sense of what sets each language apart and what tasks each language is best suited to perform.

    Chapter 11, The Bash Shell, covers Mac OS Xs default command-line interpreter in detail. You learnhow to write shell scripts that interact with command-line tools installed on your system.

    In Chapter 12, AppleScript and AppleScript Studio, you learn about Apples high-level applicationscripting language, AppleScript. AppleScript enables you to communicate with and automate tasks in MacOS X applications. You can also use AppleScript to build graphic user interfaces using AppleScript Studio.

    Chapter 13, Using Scripts Wthin Applications, illustrates how your applications can interact withcommand-line tools and other scripts. Although graphic applications and command-line tools seem verydifferent, you can easily integrate the two on Mac OS X.

    The appendix provides solutions to the exercises that appear at the end of each chapter throughout thebook.

    Appendix A, Exercise Answers, provides the solutions to the exercises that appear at the end of eachchapter throughout the book. Also be sure to check out Appendix B, Developer Resources, andAppendix C, Developer Tools Roadmap. These two appendixes offer valuable information that youmay find helpful as you develop applications.

    What You Need to Use This BookAs we mentioned earlier, your Mac OS X installation already has everything you need to get started. Youwill also need an Internet connection to access Apple Computers developer website. We used the Safariweb browser to access these pages, but other web browsers (Internet Explorer, Firefox, and so on) shouldwork fine.

    Examples and figures in this book were made using Mac OS X 10.4 Tiger and Xcode 2.0. You can fol-low along with an earlier version of Mac OS X and Xcode if you like. Although the screen shots will notmatch exactly, the code examples will still compile and run. Earlier versions of Xcode can be obtained atno charge from Apples website. You can find more information on Apples developer website, AppleDeveloper Connection, in Chapter 2.

    03_573993 flast.qxd 6/16/05 2:21 PM Page xxi

  • xxii

    Introduction

    ConventionsTo help you get the most from the text and keep track of whats happening, weve used a number of con-ventions throughout the book.

    Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

    As for styles used in the text

    We highlight important words in italics when they are introduced.

    We show keyboard strokes like this: Ctrl-A.

    We show file and folder names, URLs, and code within the text in a special monofont typeface,like this: persistence.properties.

    We present code in two different ways:

    In code examples we highlight new and important code with a gray background.

    The gray highlighting is not used for code that is less important in the presentcontext or has been shown before.

    On the WebsiteAs you work through the examples in this book, you may choose either to type in all the code manuallyor use the source code files that accompany the book. All the source code used in this book is availablefor download at www.wrox.com. Once at the site, simply locate the books title either by using the Searchbox or one of the topic lists and click the Download Code link. You can then choose what you want todownload from a list of files zipped by chapter.

    Because many books have similar titles, you may find it easiest to search by ISBN; for this book theISBN is 0-7645-7399-3 (changing to 978-0-7645-7399-6 as the new industry-wide 13-digit ISBN num-bering system is phased in by January 2007).

    After you download the code, just decompress it with your favorite compression tool. Mac OS X 10.3and later supports uncompressing zip files directly in the Finder. Alternatively, you can go to the mainWrox code download page at http://www.wrox.com/dynamic/books/download.aspx to see thecode available for this book and all other Wrox books.

    Boxes like this one hold important, not-to-be forgotten information that is directlyrelevant to the surrounding text.

    03_573993 flast.qxd 6/16/05 2:21 PM Page xxii

  • xxiii

    Introduction

    ErrataWe make every effort to ensure that there are no errors in the text or in the code. However, no one is per-fect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faultypiece of code, we would be very grateful for your feedback. By sending in errata you may save anotherreader hours of frustration; at the same time, you are helping us provide higher quality information.

    To find the errata page for this book, go to http://www.wrox.com and locate the title using the Searchbox or one of the topic lists. When the information page for the book appears, click the Errata link in themiddle of the page. On this page, you can view all errata that has been submitted for this book andposted by Wrox editors. A complete book list, including links to each books errata, is also available atwww.wrox.com/misc-pages/booklist.shtml.

    If you dont spot your error on the books Errata page, click the Errata Form link in the paragraph justabove the actual listing of errata or go to www.wrox.com/contact/techsupport.shtml. Complete theform to send us the error you have found. Well check the information and, if appropriate, post a mes-sage to the books errata page and fix the problem in subsequent editions of the book.

    p2p.wrox.comFor author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based sys-tem for you to post messages relating to Wrox books and related technologies and interact with otherreaders and technology users. The forums offer a subscription feature to email you topics of interest ofyour choosing when new posts are made to the forums. Wrox authors, editors, other industry experts,and your fellow readers are present on these forums.

    At http://p2p.wrox.com you will find a number of different forums that will help you not only asyou read this book, but also as you develop your own applications. To join the forums, just follow thesesteps:

    1. Go to p2p.wrox.com and click the Register link.2. Read the terms of use and click Agree.3. Complete the required information to join as well as any optional information you want to pro-

    vide and click Submit.

    4. You will receive an email with information describing how to verify your account and completethe joining process.

    You can read messages in the forums without joining P2P but in order to post your own messages, youmust join.

    After you join, you can post new messages and respond to messages other users post. You can read mes-sages at any time on the Web. If you would like to have new messages from a particular forum emailedto you, click the Subscribe to this Forum icon by the forum name in the forum listing.

    For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to ques-tions about how the forum software works as well as many common questions specific to P2P and Wroxbooks. To read the FAQs, click the FAQ link on any P2P page.

    03_573993 flast.qxd 6/16/05 2:21 PM Page xxiii

  • 03_573993 flast.qxd 6/16/05 2:21 PM Page xxiv

  • Part I: Mac OS XDeveloper Resources

    Chapter 1: The Mac OS X Environment

    Chapter 2: Developer Tools

    Chapter 3: Xcode

    Chapter 4: Interface Builder

    04_573993 pt01.qxd 6/16/05 2:22 PM Page 1

  • 04_573993 pt01.qxd 6/16/05 2:22 PM Page 2

  • 1The Mac OS X Environment

    Welcome to the wonderful world of Mac OS X, the next-generation operating system from AppleComputer!

    The Mac OS X operating system powers modern Macintosh computers. After many long yearsand a few scrapped attempts to modernize the older Mac OS operating system, Apple releasedMac OS X in April of 2001. Since then, Apple has released a steady stream of upgrades and systemupdates. This book was written around Mac OS X version 10.4, Tiger, the latest version.

    In order to write software for Mac OS X, you need to know your way around the system. Bynow you may already be familiar with Mac OS Xs applications and user interface style. Thosethings all rest on top of a number of subsystems and services that make up the Mac OS X operat-ing system.

    In this chapter you learn

    How the Mac OS X operating system is structured, including what the major areas of thesystem are and how they work together

    How to use Mac OS Xs command-line interface

    How applications take advantage of the operating system services on Mac OS X

    How Apple encourages a common look and feel for Mac OS X applications

    Introducing the Mac OS X What comes to mind when you think of Mac OS X? Is it the applications you use? Perhaps yourecall Mac OS Xs distinctive user interface? Or maybe you think of Mac OS Xs stability? In truth,Mac OS X embodies all these things.

    The Mac OS X operating system is often described as a collection of layers, as seen in Figure 1-1.

    05_573993 ch01.qxd 6/16/05 2:22 PM Page 3

  • Figure 1-1

    You are probably already familiar with the topmost layer: the applications that run on Mac OS X (likeMail, iTunes, Safari, and so on). These applications are all written against a collection of applicationframeworks. These frameworks are special libraries that provide the code and all the other resources(icons, translated strings, and so on) to perform common tasks. For example, the Cocoa framework con-tains a number of resources necessary to make a Cocoa application.

    All Mac OS X applications use graphics to some extent, ranging from simply presenting its user interfaceto processing graphical data like QuickTime movies. The system provides several specialized librariesfor working with graphics and graphics files.

    These layers rest on the broad shoulders of the core operating system, which at the lowest level isresponsible for making your Macintosh run. For example, the core OS handles reading from and writingto your hard drive and random access memory (RAM), it manages your network connections, it powersdown the computer when it falls to sleep, and so on. In fact, any program that talks to your hardwarein any way ultimately goes through the core OS.

    Throughout this book you examine Mac OS X in detail through Slide Master, an application that buildsand displays photo slide shows. You will build Slide Master bit-by-bit as you learn more about how theelements of Mac OS X come together. The Slide Master application and its source code can be down-loaded from Wileys website; so you can check your work against our complete solution as you go.

    This is a good time to take a quick tour of Slide Master. You can download Slide Master from Wileyswebsite, make a slide show, and view your handiwork. In doing so, you touch on all the major areas ofthe Mac OS X operating system.

    Try It Out Slide Master1. Download the files for this chapter from www.wrox.com. Refer to the Introduction for instruc-

    tions on finding the files you need from the Wrox website. You can search for the book by itsISBN number: 978-0-7645-7399-6. You are looking for a file named Chapter01.zip.

    2. Uncompress the Chapter01.zip archive using your favorite decompression tool. (Mac OS X10.3 and later supports uncompressing .zip files directly in the Finder.) Inside you will find theSlide Master application, a folder of pictures called Images, and a folder of source code.

    3. Run the Slide Master application by double-clicking it in Finder. The application opens an unti-tled document window.

    4. Add the pictures in the Images folder to Slide Master by choosing Slide Show Add Slide. Youcan select all the files at once from the open panel. The images appear in a drawer to the side of thedocument window and the main window displays the selected image, as shown in Figure 1-2. Youcan use the arrow keys to change the selection.

    Applications

    Frameworks and UI

    Graphics and Media

    Core Operating System

    4

    Chapter 1

    05_573993 ch01.qxd 6/16/05 2:22 PM Page 4