Sams Cocoa Programming Sep 2002 ISBN 0672322307 pdf

  Cocoa ® Pr ogr a m m in g By

Publisher: Sam s Publishing

  Pub Dat e: Sept em ber 20, 2002

  

I SBN: 0- 672- 32230- 7

Pages: 1272

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  Book : Cocoa® Program m ing Copyright

  Copyright © 2003 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. Library of Congress Catalog Card Number: 2001089381 Printed in the United States of America First Printing: September 2002 05 04 03 02 4 3 2 1

  Trademarks

  All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

  Warning and Disclaimer

  Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an "as is" basis. The author(s) and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

  Credits Executive Editor

  Jeff Schultz

Acquisitions Editor

Betsy Brown

Development Editor

Susan Hobbs Managing Editor Charlotte Clapp Project Editors Elizabeth Finney Katelyn Cozatt Copy Editor Chip Gardner Indexer Chris Barrick Proofreaders Andrea Dugan Jody Larsen Technical Editors John Ray Steve Munt

Team Coordinator

  Amy Patton

Interior Designer

Gary Adair Cover Designer Alan Clements Page Layout

D&G Limited, LLC

  Book : Cocoa® Program m ing About the Authors Scott Anguish

  Upon seeing the NeXT development environment in 1992 he was hooked on the possibilities of a unified imaging model and a pure object-oriented system. In 1994, after several years of NeXT development, he created Stepwise, a portal for information related to NeXT technologies. Today, Stepwise serves as a hub for Apple's Mac OS X technology platform as well as Cocoa and WebObjects development. During the day he works to build better technology for the Center for Educational Technology at Middlebury College using Cocoa and WebObjects, of course.

  Erik M. Buck ) is President of EMB & Associates, Inc., a

  technology leader in the aerospace and entertainment software industries. He is a contributor to Stepwise and has been developing software with Cocoa and its predecessor technologies, OPENSTEP and NeXTSTEP, professionally since 1989. Mr. Buck holds a BS in Computer Science from the University of Dayton.

  Donald A. Yacktman ( ) has been using Cocoa and its predecessor

  technologies, OPENSTEP and NeXTSTEP, professionally since 1991. He is currently the Vice President of Development at illumineX, inc. illumineX is both an independent software vendor of Cocoa-based Mac OS X software and a WebObjects consulting firm.

  Mr. Yacktman is a member of the Stepwise editorial staff and the principal contributor to the MiscKit, a premier source of information and reusable software for the OPENSTEP and Cocoa communities. He holds BS and MS degrees in Electrical and Computer Engineering from Brigham Young University and has been programming professionally since 1981.

  Book : Cocoa® Program m ing Acknowledgments Scott Anguish

  I would like to thank my wife Dorothy and my kids, Simon and Tori, for their love and support while I was working on this project. This book would have been much thinner if not for the heroic efforts of Don and Erik. I'd also like to thank the folks who contribute to the community and Stepwise in particular. I too have a long list of Cocoa programmers and developers who should be thanked both outside of Apple and within. I hope that we can continue this journey of Cocoa development for years to come.

  Erik M. Buck

  I would like to thank my wife Michelle and family for their support, which made writing the book both possible and enjoyable. I would also like to thank Don Yacktman, Scott Anguish, and the many supportive people who contribute to Stepwise and the community of Cocoa developers. Finally, I would like to thank the Cocoa programmers and enthusiasts for whom this book was written. It is my sincere hope that this book will both accelerate the process of learning Cocoa and help make using Cocoa fun.

  Don Yacktman

  I would like to thank my wife Marcie for her patience and support during the writing of this book. The support of my entire family is also greatly appreciated. I would also like to thank my co-workers at illumineX, especially CEO Gary Longsine, for their patience and understanding. Without the support of Marcie and Gary, this book would not have been possible. Many thanks are offered to the numerous friends at Apple who have taken time to verify facts in this book. Finally, I would like to thank all the people who helped me learn the skills used and described in this book. The people who have offered help and guidance over the years are too numerous to list, but this book exists in part because of their contributions.

  Book : Cocoa® Program m ing We Want to Hear From You!

  As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way.

  You can email or write me directly to let me know what you did or didn't like about this book-as well as what we can do to make our books stronger.

  

Please note that I cannot help you with technical problems related to the topic of this book,

and that due to the high volume of mail I receive, I might not be able to reply to every message.

  When you write, please be sure to include this book's title and authors as well as your name and phone or email address. I will carefully review your comments and share them with the authors and editors who worked on the book.

  Email: Mail: Mark Taber

  Associate Publisher Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA

  Book : Cocoa® Program m ing Reader Services

  For more information about this book or others from Sams Publishing, visit our Web site at

  

the Search box to find the book you're looking for.

  Book : Cocoa® Program m ing Introduction

  Software development for Mac OS X can be a great joy. The advanced programming tools and frameworks now provided by Apple astound many programmers. When programmers delve into the object-oriented technology called Cocoa, which is part of every Mac OS X system, they often describe the experience as life-changing. Claims of massive productivity increases are common. Developers describe Cocoa as eye-opening. Cocoa demonstrates the true power of object-oriented programming in a way that few programmers have experienced when using other technologies. Cocoa enables programmers to focus on the unique value of their applications by eliminating almost all the drudgery traditionally necessary when making complex graphical applications. The Cocoa technology exemplifies some of the best software design ever seen. Beyond providing tremendous functionality out of the box, the Cocoa technology inspires programmers to follow Apple's example and design excellent software.

  Apple acquired much of the Cocoa technology in the last days of 1996 when Apple merged with a company called NeXT. When first seen publicly in 1988, the technology was called NeXTSTEP. Over the years NeXTSTEP became OPENSTEP, then Rhapsody, then Yellow Box, and finally Cocoa. Each name change brought additional features and maturity. Apple has significantly expanded and enhanced Cocoa for Mac OS X.

  Although there are many ways to program an Apple computer, this book focuses on the Cocoa environment. Using Cocoa is the most advanced and arguably the most productive way to program a Macintosh-it's also the most fun. In presentations to developers, Apple representatives describe Cocoa as the future. Apple recommends that all new software development for the Mac use Cocoa.

  This book contains all of the information necessary to build complex Cocoa applications. The major Cocoa concepts are explained and demonstrated with example code. With this book, an experienced developer can become immediately productive with Cocoa and Mac OS X.

  Se ct ion : I nt roduct ion Book : Cocoa® Program m ing Intended Audience

  This book is intended for intermediate and advanced programmers who are familiar with C programming and many of the concepts of object-oriented programming. No prior experience with Mac OS X or other Apple products is required, but the reader must have access to a computer running Mac OS X and the Apple-provided development tools to use the example programs. Object orientation and a small set of object-oriented extensions to the C language are explained in this book, but this book is not a substitute for a comprehensive language reference or books solely dedicated to object technology. The two computer languages that Apple suggests for use with Cocoa are Java and Objective-C. Java is discussed, but the examples in this book are primarily implemented with Objective-C. Objective-C is the language in which Cocoa was written, and the reasons for choosing Objective-C are presented in the book.

  Programmers familiar with other development technology including PowerPlant, Mac App, MFC/Win32, and Java Swing might experience culture shock when first learning Cocoa. Even though the core of Cocoa has been in use for more than a decade, it is still revolutionary. Revolutions do not always occur without discomfort, but few programmers ever look back after experiencing Cocoa. A common question posed after learning Cocoa is "why haven't we been doing it this way all along."

  Se ct ion : I nt roduct ion Book : Cocoa® Program m ing Conventions The following typographical conventions are used throughout this book.

  Italic type is used for introducing new terms and usage notes.

  type is used for code examples, command-line output, filenames and file

  Monospace system paths, data types, URLs, and symbolic constants.

  Bold Monospace type is used for required user input in examples.

  Italic Monospace type is used to designate a placeholder for user input.

  Se ct ion : I nt roduct ion Book : Cocoa® Program m ing Learn By Example

  Each major topic in this book is accompanied by a self-contained example. Examining and modifying the examples is often the best way to learn a new development environment and technology. Readers are encouraged to play with example code, experiment, and test their understanding. In many cases, the code in the examples can be copied into a new project to provide a jump-start. The authors have more than 30 years of collective experience with this technology. The examples embody the best practices, common programming idioms, and wisdom acquired by the authors.

  There is a web site associated with this book at . All the example code found in this book and more can be obtained from the Web site. The code is organized on the Web site by chapter and example name. Any updates to the material in this book, including errata, can be found there.

  Book : Cocoa® Program m ing

  Part I: Overview IN THIS PART

  

  

  

  

  

  

  Se ct ion : Part I : Overview Book : Cocoa® Program m ing

Chapter 1. Cocoa and Mac OS X IN THIS CHAPTER

  

  Cocoa is a collection of software objects that implements almost all features common to Mac OS X applications. Programmers extend the Cocoa objects to implement application- specific features. The Cocoa objects are reused in every Cocoa application so that programmers can concentrate on adding unique value with each line of code rather than constantly reimplementing common features or struggling to access operating system services. Significant applications can be built with very little code.

  Cocoa is the result of continuous evolution from the software development environment of NeXTSTEP, which was first released to the public in 1988. Cocoa takes advantage of common object-oriented design patterns and best practices. In fact, many of the common design patterns were first recognized in NeXTSTEP. Cocoa design patterns are described

Chapter 6 , "Cocoa Design Patterns." Cocoa is distinguished from other object-oriented development environments in several

  ways: Cocoa is mature, consistent, and broad. Cocoa is based on a cross-platform specification and has evolved from a cross-platform implementation. Cocoa is extraordinarily extensible, flexible, and dynamic in part because of Objective-C, the

Chapter 4 , "Objective-C." Cocoa emphasizes the reuse of objects, dynamic loading of objects, and messaging between objects. Many developers enjoy huge programmer productivity improvements by using Cocoa

  instead of other technologies. Several ground-breaking applications were originally developed with NeXTSTEP, including Apple's own Interface Builder, Lotus Improv, and the first World Wide Web browser. The initial implementations of the famous games Doom and Quake, and the custom development tools for the games were written using the predecessors to Cocoa. Developers such as Tim Berners-Lee, who invented the World Wide Web, claim that they could not have created cutting edge applications as easily if they had to use other technologies. The obstacles to overcome in other environments would have hampered the innovations.

  NOTE

  Screen shots of the first Web browser and commentary from Berners-Lee are

  Se ct ion : Chapt er 1. Cocoa and Mac OS X Book : Cocoa® Program m ing Understanding When to Use Cocoa

  To understand why you would choose to use Cocoa, it is necessary to briefly explain the alternatives. Apple supports three principal software development environments for producing Mac OS X applications. The supported environments are Cocoa, Carbon, and 100% Pure Java. Each environment has strengths and weaknesses, and a developer's choice of environment is influenced by many factors.

  Carbon

  Carbon consists primarily of a subset of the traditional procedural Application Programming Interfaces (API)s used to program Mac computers. Apple updated, and in some cases, enhanced the C libraries used to program Macs before OS X. Carbon provides access to the modern and powerful features of OS X in a way that preserves compatibility with most of the software written for earlier Mac operating systems. Applications written using Carbon work on Mac OS 8 or Mac OS 9 with compatibility libraries installed, and on Mac OS X. Apple provides a free application called CarbonDater that analyzes software for compatibility with Carbon. In many cases, programmers can easily convert old applications written for the Mac to work with Carbon on OS X.

  Cocoa applications do not work with Mac operating systems prior to OS X. If compatibility with Mac OS 8 or 9 is required, Carbon might be the best choice. On OS X, one advantage of Cocoa is that Cocoa programs written with the Objective-C language can freely call the C-based Carbon APIs. It is much more difficult for Carbon applications to benefit from Cocoa features. In some cases, Apple has already implemented Cocoa objects that shield programmers from underlying Carbon implementations.

  The difficulty accessing Cocoa features from Carbon is expected to decline over time. Carbon is slowly gaining access to traditional Cocoa features. Cocoa solutions to common programming problems are preferred, and Apple has already exposed some parts of Cocoa to Carbon programs. For example, the Core Foundation API is used extensively in Carbon applications. Core Foundation is a procedural interface to the features of Cocoa objects. In some cases, Core Foundation functions are derived from previously private internal implementations of Cocoa objects.

  Java

  Java is both programming language and a set of cross-platform libraries. Mac OS X comes with a complete implementation of Sun's Java 2 Standard Edition version 1.3.1. Apple's Java Virtual Machine was developed in cooperation with Sun and uses many Sun applications can be developed on OS X using Apple's developer tools or third-party tools. 100% Pure Java applications are portable to many different operating systems. If portability is the primary requirement for a software project, 100% Pure Java might be the best development technology. Java can be used to develop Cocoa applications, but the resulting applications only work on Mac OS X. The objects that comprise Cocoa are written in Objective-C, but Apple provides a technology called the Java Bridge that enables relatively seamless use of Cocoa objects from Java code and vise versa. Objective-C was one of the major influences that shaped the design of the Java language. Java and Objective-C have many similarities under

   , "Cocoa Language Options." Cocoa

  Cocoa is the most mature development environment for OS X, as well as the most productive technology for implementing many types of applications. The cheapest, fastest, and most bug-free lines of code in any application are the lines a programmer didn't have to write. Cocoa's pervasive use and reuse of objects dramatically reduces the number of lines of code in applications. By following the example set by Cocoa, many developers achieve high levels of reuse with their own custom objects.

  A simple comparison is the TextEdit application shipped with OS X versus the SimpleText Carbon example that Apple provides with their developer tools. TextEdit is a Cocoa application implemented in 1354 lines of code, whereas SimpleText is implemented in 5231 lines of code. TextEdit has many more features and fewer limitations than SimpleText, yet TextEdit requires approximately 1/4 the number of lines of code. Cocoa programmers often claim a 5-1 productivity advantage over alternative technologies, however, the TextEdit verses SimpleText comparison indicates a much greater advantage than 5-1.

  Cocoa is the most flexible software development technology for Mac OS X. Cocoa is written in Objective-C, and that provides several advantages. Objective-C is a small superset of ANSI C. Objective-C programs can seamlessly use all the C libraries available in OS X, including Carbon and traditional Unix libraries. A variant of Objective-C called Objective-C++ includes support for direct use of C++ libraries along with Cocoa. Apple's Java bridge technology enables Java programs to use Cocoa, and allows Objective-C Cocoa applications to use existing Java libraries. Apple has even provided access to Cocoa from AppleScript, therefore, it is possible to write full-featured applications using AppleScript and Cocoa. Cocoa is the only development environment for Mac OS X that directly enables use of all other system components.

  Cocoa is the most extensible software-development technology for Mac OS X. It is for Cocoa. All Cocoa applications can take advantage of the addition without even being recompiled. It is possible to selectively replace Cocoa objects with custom versions. Cocoa provides powerful features for dynamically loading objects such as plug-ins. The dynamic loading capabilities of Cocoa are only partly available to Carbon programs. It is even possible to completely change the user interface of a Cocoa application without access to the application's source code.

  Se ct ion : Chapt er 1. Cocoa and Mac OS X Book : Cocoa® Program m ing Understanding Cocoa's Role in Mac OS X Mac OS X traces its heritage to earlier Mac operating systems and to versions of Unix.

  Mac OS X melds the two operating systems into one. enable access to all the features of OS X. Cocoa applications can use the Quartz, OpenGL, and QuickTime graphics systems supported by Mac OS X. Cocoa provides high-level, object-oriented components that use Quartz and advanced font rendering capabilities built on top of Quartz. Cocoa objects exist to access OpenGL and QuickTime. Traditional Mac features are accessed through objects that internally use the Carbon API. Cocoa directly uses features provided by Darwin.

Figure 1.1. Mac OS X uses a layered architecture.

  Cocoa contains objects that use the networking and file system features of Darwin. Many Cocoa objects are implemented to use the Core Foundation components of Darwin. The Objective-C language runtime used by Cocoa is implemented in Darwin.

  Quartz

  Quartz is the term used to collectively identify the advanced 2D graphics capabilities of OS X, which are built on top of Darwin. Quartz consists of a window server process and a

  The window server is a process that runs in the background and controls display access by applications. The window server provides device-independent color capabilities and color correction for displays. The window server manages the layering of windows owned by different applications and implements features such as translucency and live-window dragging. The window server can reposition windows, apply translucent drop shadows, and layer translucent windows without interrupting other applications. The window server also provides limited direct access to the video frame buffer for games, OpenGL, and QuickTime.

  In addition to the window server, Quartz provides a graphics-programming API called Core Graphics. Core Graphics provides functions and data types that can be used from any of the programming environments supported by Mac OS X. In essence, Core Graphics is an API for producing graphics compatible with the powerful cross-platform Portable Document Format (PDF) standard from Adobe.

  Core Graphics provides device-independent vector and bitmap graphics operations with support for antialiasing and transparency. Core graphics has set a new high standard for the presentation quality of graphics on a computer screen. Almost any graphics drawn with Core Foundation can be saved as PDF files for viewing on any computer with a PDF viewer. PDF is rapidly becoming the preferred format for What You See Is What You Get (WYSIWYG) printing and publishing.

  Cocoa's use of Quartz and 2D graphics is described in

   OpenGL OpenGL is a standard cross-platform API for hardware accelerated 2D and 3D graphics. Mac OS X features optimized OpenGL drivers, and every recent Mac computer ships with

  hardware accelerated 3D graphics support. OpenGL is one of the most widely adopted graphics standards. It is available for Unix and Microsoft Windows in addition to OS X. Code that uses OpenGL can be very portable and produces consistent results across many platforms. OpenGL is frequently used to implement games, medical imaging software, and engineering applications. Cocoa includes an object for interfacing with OpenGL.

  QuickTime

  QuickTime is an Apple proprietary cross-platform technology for creating and presenting video, animation, sound, music, and virtual reality environments. QuickTime is extensible and supported for versions Mac OS 8 and higher, as well as all recent versions of Microsoft Windows. Mac OS X provides up-to-date QuickTime support including programming APIs, real-time streaming, and viewers.

  QuickTime supports common graphics file formats for still images and video. QuickTime can be used with popular Internet protocols for streaming media, and plug-ins exist for most Web browsers including Internet Explorer, Netscape Navigator, and America Online. Cocoa provides an object that enables the use of QuickTime from Cocoa applications. Apple provides sample reusable objects that extend Cocoa's built-in support for QuickTime and enable the creation of simple movie editors without writing any code at all.

  Darwin

  Darwin is Apple's name for the lowest-level components in Mac OS X. Cocoa is implemented using the features of Darwin. Darwin consists of components that provide core essential services. The Mach kernel is the heart of Darwin. Device drivers, file systems, networking, Unix APIs, support for kernel extension, the Objective-C language runtime, and key programming APIs are all part of Darwin.

  Darwin source code is available from Apple under the terms of Apple's flexible open- source license. By registering with Apple, any developer can download the Darwin source code. Ports of Darwin already exist for the Intel x86 family of processors. By making Darwin open source, Apple has empowered the broad community of Unix developers to inspect and enhance the lowest-level core of Mac OS X. Third-party developers have already contributed security enhancements and other features back to Apple.

  Mach

  Mach is the core of Mac OS X, and every software development technology in Mac OS X uses the features of Mach. The version of Mach used in OS X is based on Mach 3.0. Mach schedules CPU usage, supports symmetric multiprocessing with multiple CPUs, provides memory protection and dynamic virtual memory, provides real-time features, and implements an interprocess messaging system used by higher-level components to interface with the kernel.

  Cocoa objects that manage processes, threads, and interprocess communication use features of Mach directly in their implementations. All Cocoa objects benefit from the memory protection, dynamic virtual memory, and real-time features provided by Mach.

  Device Drivers In some cases, Cocoa objects use the features of operating system device drivers directly.

  For example, Cocoa provides support for digital graphic tablets, mouse scroll wheels, and multiple mouse buttons by interoperating with the relevant device drivers. Device drivers for OS X are built as Mach kernel extensions. New device drivers can be dynamically loaded into a running Mach kernel. There is no need to recompile the kernel or even shut down the machine to install new device drivers.

  Many Cocoa objects use traditional Unix features in their implementation on Mac OS X. The Darwin component called Berkley Standard Distribution (BSD) refers the University of California-Berkley standard distribution of Unix. The Berkley variant is one of the major branches on the Unix family tree. Several free implementations of BSD Unix are available. Apple uses code from some of the free versions in OS X and has contributed back to them as well. Mac OS X's Unix features are principally based on standard BSD 4.4 with networking components from FreeBSD 3.2.

  Networking

  Cocoa provides objects that enable seamless access to networking features of the operating system. Darwin includes networking support implemented as extensions to the Mach kernel. Most of the networking components are based on the network support architecture implemented in FreeBSD 3.2. Most of the POSIX standard API to access networking features via sockets is supported. Sockets-based communication originated with early versions of BSD Unix and has since become the most common technique. Sockets are supported by every recent version of Unix and Microsoft Windows.

  File Systems

  Cocoa relies on Darwin for file system support. Cocoa provides objects that abstract file system-specific issues. Cocoa programs work regardless of the underlying file system. The abstraction is particularly important because modern operating systems such as Mac OS X support so many different file systems. Avoiding the need to write code to handle different file system issues is an advantage of Cocoa.

  Darwin includes advanced file system support implemented in a layer outside the Mach kernel. Mac OS X already supports Unix File System (UFS), Hierarchical File System plus (HFS+), ISO 9660, File Allocated Table (FAT), Network File System (NFS), Web-based Distributed Authoring and Versioning (WebDAV), and Universal Disk Format (UDF). UFS is a common Unix file system. HFS+ is the native file system used by prior Mac operating systems. HFS+ is the file system recommended by Apple because it best preserves compatibility with software written for prior Mac operating systems. The ISO 9660 file system is standard and commonly used on CD-ROMS. The FAT file system is used by Microsoft DOS and some Microsoft Windows installations. NFS implements a standard protocol for accessing file systems on one machine from another over a network. WebDAV is the file system implemented as extensions to the HTTP protocol. Apple uses WebDAV to provide remote access to each user's iDisk. An iDisk is simply storage allocated on a hard disk on a server at Apple. Mac users can use the storage to share files with other people over the Internet. UDF is a file system intended to replace the ISO 9660 file system. UDF is primarily used on DVDs.

  Objective-C Runtime

  One of the most critical features of Darwin that is used by Cocoa is Apple's Objective-C runtime. Cocoa is written in Objective-C. Apple uses the open source GNU Compiler Collection (gcc) compiler and provides the basic compiler and development tools for use with Darwin as a free download in source code or binary form. gcc is part of the Free Software Foundation's GNU project. The gcc compiler collection comes with Objective-C support, and a GNU Objective-C runtime that is slightly different from the one shipped with Apple's Darwin. Apple has stated plans to keep their own version of gcc synchronized with the standard GNU version and possibly unify the two Objective-C runtimes in the future.

  Parts of Core Foundation

  Darwin includes part of the implementation of the Core Foundation procedural APIs. Core Foundation is used by many of the higher-level APIs of Mac OS X includ-ing Cocoa.

Chapter 7 , "Foundation Framework Overview," includes a brief introduction to the Core Foundation. The fact that some source code for Core Foundation is available with Darwin

  opens opportunities for third parties to inspect and enhance key elements of OS X's software development infrastructure.

  Se ct ion : Chapt er 1. Cocoa and Mac OS X Book : Cocoa® Program m ing What You Need to Use Cocoa

  Apple provides everything needed to develop Cocoa applications for Mac OS X. Apple's developer tools are shipped on a CD-ROM in the same box with the Mac OS X operating system CD-ROM. Cocoa can be used with Java, AppleScript, C++, and other languages, but knowledge of C is required in most cases. The Cocoa objects are written in Objective-C.

  This book provides an introduction to Objective-C for programmers who are already familiar with C. Objective-C consists of a small set of extensions to ANSI standard C. C programmers with experience using one or more object-oriented languages can learn Objective-C very quickly. When Objective-C is familiar, the more daunting task of learning the large and sometimes complex Cocoa frameworks begins.

  The Cocoa frameworks are an excellent example of the power of object-oriented programming and Objective-C. Even though Cocoa is large and provides many features, it is consistent. The consistency helps programmers learn new parts of Cocoa by extending knowledge already gained. After a while, programmers often find themselves reusing Cocoa designs and programming idioms in their own code. Many programmers reaction to Cocoa is "why was software ever written another way?"

  Se ct ion : Chapt er 1. Cocoa and Mac OS X Book : Cocoa® Program m ing What's Included in Cocoa

  Cocoa is composed of frameworks that contain libraries of objects and related resources, data types, functions, header files, and documentation. The two major Cocoa frameworks are the Foundation framework and the Application Kit framework. Cocoa frameworks and the Mac OS X system components used by the frameworks.

Figure 1.2. Cocoa contains layered frameworks of objects.

  The Foundation framework, shown in useful in every Cocoa application. The Foundation framework uses the services provided by Darwin, and provides a foundation for other frameworks and applications to extend. The Application Kit framework is built using the Foundation framework and OS X's graphics services that are, in turn, built on top of Darwin. The Application Kit provides graphical objects and graphical user interface elements. The Application Kit framework provides the look and feel of Mac OS X Cocoa applications. The Yellow Box version of the Application Kit provided Microsoft Windows, OpenStep, or traditional Mac OS looks on each platform, but the Application Kit on OS X only supports Apple's Aqua look and feel. Cocoa is implemented in Objective-C. Objective-C is a dynamic language that supports a style of flexible programming well-suited to creating reusable objects and accommodating evolutionary change. Cocoa applications consist of interconnected objects. Apple provides some of the objects, and others are provided by other vendors. Finally, applications contain custom application-specific objects. The objects communicate with each other by sending messages, and all objects are equal. The objects that Apple provides are not special in any way. Custom objects, third-party objects, and Apple's objects all work together even

  Apple provides several applications that contribute to the productivity of Cocoa programmers. Not surprisingly, most of Apple's own developer tools are Cocoa applications. Mac OS X is built using Cocoa applications. Even the Apple tools used to write Carbon and Java programs are Cocoa applications.

  Se ct ion : Chapt er 1. Cocoa and Mac OS X Book : Cocoa® Program m ing Summary

  Cocoa is an advanced, mature, flexible, and extensible software development technology that uses frameworks of objects and related resources. Cocoa has a legacy of cross- platform support. Cocoa applications have access to all features of Mac OS X. Cocoa provides large programmer productivity advantages compared to other technologies available for software development on Mac OS X, but Cocoa applications only run on Mac OS X. Carbon and 100% Pure Java are alternative technologies that support multiple platforms.

  The rest of this book explores Cocoa software development in detail. You'll start with

Chapter 2 , "Cocoa Language Options," which covers the range of languages used to develop Cocoa applications.

  Se ct ion : Part I : Overview Book : Cocoa® Program m ing

Chapter 2. Cocoa Language Options IN THIS CHAPTER

   Cocoa is a collection of object-oriented components written in the Objective-C language.

  Objective-C is a flexible and dynamic language that adds object-oriented extensions to ANSI standard C. Because of the flexibility of Objective-C, the Cocoa components can be used by a wide variety of languages besides Objective-C. The key language elements needed to use Cocoa are support for dynamic object orientation and compatibility with the C programming language.

  This chapter describes the general features of all languages that can be used with Cocoa, and a brief overview of object-oriented terminology. Details about the most common languages used with Cocoa are provided. The available language options are explained along with some of the advantages and disadvantages of different languages. This book primarily uses the Objective-C language, and this chapter explains why.

  Java and many scripting languages provide the required language features to use Cocoa directly. Other languages such as C and C++ are not sufficiently dynamic to use Cocoa objects directly. C and C++ programs can access Cocoa in two ways: They can use Cocoa indirectly via the C-based Objective-C runtime, or they can be recompiled using the Objective-C and Objective-C++ language compilers.

  Details about using the Objective-C runtime from C or C++ without using the Objective-C Because Objective-C is an extension of standard C and can compile all C programs, the best way to use Cocoa from C code is to actually use Objective-C. Parts of a program can be standard C (perhaps for portability reasons), whereas other parts can use Objective-C's object-oriented extensions to access Cocoa. A variant of Objective-C called Objective-C++ provides the same object-oriented extensions to C++ that Objective-C provides to standard C. The best way to mix C++ code and Cocoa is to use Objective-C++.

  Se ct ion : Chapt er 2. Cocoa Language Opt ions Book : Cocoa® Program m ing Object Orientation

  Cocoa is a collection of objects. To understand how various languages use Cocoa, a brief explanation of objects and object orientation is needed. Object-oriented languages must use objects in a way that is compatible with Cocoa to be integrated with Cocoa. For example, Java is an object-oriented language that interfaces well with Cocoa. C++ is an object- oriented language that provides a model of objects incompatible with Cocoa.

  The goals of object orientation are to make writing software easier, cheaper, and faster. The principal way that object orientation achieves its goals is through software reuse. The idea is that software can be organized into objects that are individually reusable. Each time a new software project begins, substantial parts of the project can be implemented using existing software objects. In theory, the only new code that is written for a project is the code that is truly unique to that project and cannot be shared by other projects.

  By reusing objects, programmers hope to reduce the amount of new code written for each project and, therefore, finish the project faster. Reused objects are already well-tested in other projects. By reusing objects, programmers avoid bugs that might be created in new code. Existing objects that implement complex logic are used to make creating software for a new project easier. The idea is that the most complex and difficult to write code is provided by existing objects. Reusing objects is simpler than rewriting the logic implemented by the objects.

  Encapsulation

  Encapsulation is one of the principal ideas of object orientation. Encapsulation means that data and the logic that operates on the data are grouped together. Data is only modified via the operations encapsulated with the data. Encapsulation aids reuse and simplifies software maintenance. Encapsulation also ensures that related data and logic can be easily identified in one project and reused in another. Because data and logic are encapsulated together, it is not necessary to grab a line of code here and a data structure definition there, or search all the source code in a project for necessary lines of code to reuse just one feature of a project. Encapsulation aids software maintenance by localizing problem solutions. If a bug is detected, or a new feature must be added, encapsulation ensures that there is only one place in the code where changes are made. Without encapsulation, fixing a bug, or adding a feature might require changes to many different parts of a software project.

  Modularity

  Modularity is related to encapsulation. Modularity is the practice of implementing a idea is that modules of code and data can be developed and compiled independently. The separately compiled modules are brought together to complete a project. In many cases, each module encapsulates some data and logic. Apple's Objective-C compiler enables the use of multiple modules to encapsulate one set of data and operations. It is also possible to implement multiple units of encapsulation in one module, but it is usually a bad practice.

  Classes In most object-oriented languages, something called a class is the basis of encapsulation.

  Each class encapsulates some data and all operations upon that data. Operations on data are sometimes called behaviors. Classes are implemented in one or more modules. Classes formalize the ideas of encapsulation, and in some languages the compiler enforces that encapsulation. The compiler prevents code that is not part of a class from modifying the data managed by the class. Classes are related to instances and inheritance.

  Instances

  A class is in some respects an abstract idea. A class describes data and operations on that data, but a class by itself is usually just an idea. For example, imagine a class called that describes certain characteristics of all graphical user interface elements.

  Control

  Those characteristics might include color and position. The class Control is not any particular user interface element, it describes all user interface elements. A particular button is an "instance" of the class . An instance of the class has a

  Control Control color and a position as described by the Control class.

  A class describes data and behavior. An instance actually stores the data described by a class. There can be any number of instances of a class. The behaviors defined in a class are applied to instance's data.

  NOTE

  You will learn more about abstract classes and abstract Cocoa classes in Chapters

  

Chapter 4 also introduces the details of Objective-C as well

  as class methods versus instance methods. If these concepts are confusing to you now, you'll get more details in these two chapters.

  Objects Both classes and instances can be called objects. Classes are objects that describe instances.

  Instances are objects that store data described by a class. Object is a general term that applies to encapsulated data and logic and has different implications in different languages. encapsulation, such as support for specialization.

  Specialization

  Object orientation promotes software reuse. Software objects from one project can be used in another project. But what happens when a new project needs an object similar to one that already exists, but needs just a few changes? The existing object can be specialized rather than starting from scratch to create a new object that meets the exact needs of the new project. Specialization is a technique for altering parts of the data and behavior of an existing object while reusing other parts. There are two types of specialization: instance- based and class-based. Cocoa uses both class-based specialization and instance-based specialization extensively.

  Instance-based specialization is a technique for changing the behavior of just one instance object without necessarily modifying the behavior of other instances of the same class.

  Class-based specialization applies changes to classes. The most common technique is to create a new class that includes all the data and operations of another class while adding additional data and new behaviors. Instances of the new class store the additional data and have the additional behaviors along with the data and behaviors of instances of the original class.

  Inheritance

  Inheritance is the most common form of class-based specialization. If a class called includes the data and behaviors of class , class is said to

  Button Control Button

  inherit from class Control . The terms subclass and superclass describe the inheritance relationship. is a subclass of . A subclass inherits all of the data and

  Button Control

  behavior of its superclass. In this example, is 's superclass. If class

  Control Button

  inherits from class , an instance of can be used in any context

  Button Control Button that an instance of Control is required.

  Some languages such as C++ support multiple inheritance. Multiple inheritance means that a class has all the data and behavior described by two or more super classes. Java and Objective-C do not support multiple inheritance, and Cocoa does not use multiple inheritance.

  Messages

  Messages are one way that objects can communicate with each other. Messages enable objects to request that other objects invoke behaviors. A user interface object might send the message to a instance as a way to request that the

  

isEnabled Control Control

  instance returns a or value. A message is an abstract idea and few assumptions are

YES NO

  sender of the message might not know the class of the receiver. The receiver might not even be in the same program as the sender. Messages promote object reuse by minimizing the dependencies between objects. The less one object knows about another, the better chance the objects can be reused separately. Messaging enables communication between objects without dependencies.

  Many object-oriented languages do not directly support messaging. Messaging is one of the dynamic features of Objective-C that are essential to the implementation of Cocoa. Messaging is described in