OReilly Cocoa In A Nutshell May 2003 ISBN 0596004621 pdf

  [ Team LiB ] [ Team LiB ]

  • Table of Cont ent s • Table of Cont ent s

  I ndex I ndex • •

  • Reviews Reviews • • Reader Reviews Reader Reviews

  Errat a • • Errat a Cocoa in a N u t sh e ll Cocoa in a N u t sh e ll By By , ,

  Michael Beam Michael Beam Jam es Duncan Davidson Jam es Duncan Davidson Publisher: O'Reilly Publisher: O'Reilly Date Date

  : May 2003 : May 2003 Published Published

  I SBN: 0- 596- 00462- 1 Pages: 566 Pages: 566

Cocoa in a Nut shell begins w it h a com plet e overview of Cocoa's obj ect classes. I t provides developers Cocoa in a Nut shell begins w it h a com plet e overview of Cocoa's obj ect classes. I t provides developers

who m ay be experienced wit h ot her applicat ion t oolkit s t he grounding t hey'll need t o st art developing who m ay be experienced wit h ot her applicat ion t oolkit s t he grounding t hey'll need t o st art developing

Cocoa applicat ions. A com plem ent t o Apple's docum ent at ion, it is t he only reference t o t he classes, Cocoa applicat ions. A com plem ent t o Apple's docum ent at ion, it is t he only reference t o t he classes,

funct ions, t ypes, const ant s, prot ocols, and m et hods t hat m ake up Cocoa's Foundat ion and Applicat ion funct ions, t ypes, const ant s, prot ocols, and m et hods t hat m ake up Cocoa's Foundat ion and Applicat ion

Kit fram eworks, based on t he Jaguar release ( Mac OS X 10.2) . Kit fram eworks, based on t he Jaguar release ( Mac OS X 10.2) .

  I SBN: 0- 596- 00462- 1

  [ Team LiB ] [ Team LiB ]

  [ Team LiB ] Table of Cont ent s • I ndex • Reviews • Reader Reviews • Errat a •

  Cocoa in a N u t sh e ll By ,

  Michael Beam Jam es Duncan Davidson Publisher: O'Reilly Date

  : May 2003 Published

  I SBN: 0- 596- 00462- 1 Pages: 566 Copyright Preface

  What I s Cocoa? How This Book I s Organized Convent ions Used in This Book

How t he Quick Reference Was Generat ed

Com m ent s and Quest ions Acknowledgm ents

  Part I : I nt roducing Cocoa Chapt er 1. Obj ect ive- C Sect ion 1.1. Obj ect s Sect ion 1.2. Messaging Sect ion 1.3. Classes Sect ion 1.4. Creat ing Obj ect I nst ances

Sect ion 1.5. Mem ory Managem ent

Sect ion 1.6. Deallocat ing Obj ect s

Sect ion 1.7. Cat egories

Sect ion 1.8. Nam ing Convent ions

Chapt er 2. Foundat ion Sect ion 2.1. Dat a Sect ion 2.2. Key- Value Coding Sect ion 2.3. Working wit h Files Sect ion 2.4. Bundles and Resource Managem ent

  Sect ion 2.5. Archiving Obj ect s Sect ion 2.6. User Default s Sect ion 2.7. Not ificat ions Sect ion 2.8. Operat ing Syst em I nt eract ion

Sect ion 2.9. Threaded Program m ing

Chapt er 3. The Applicat ion Kit

Sect ion 3.1. AppKit Design Pat t erns

Sect ion 3.2. Nibs

Sect ion 3.3. Applicat ion Archit ect ure

Sect ion 3.4. Cont rols Sect ion 3.5. Menus Sect ion 3.6. Sheet s Sect ion 3.7. Drawers Sect ion 3.8. Toolbars Sect ion 3.9. Event Handling Sect ion 3.10. Docum ent - Based Applicat ions

  Chapt er 4. Drawing and I m aging Sect ion 4.1. The Role of Quart z Sect ion 4.2. Coordinat e Syst em s Sect ion 4.3. Graphics Cont ext s Sect ion 4.4. Working wit h Pat hs Sect ion 4.5. Drawing Text Sect ion 4.6. Working wit h Color Sect ion 4.7. Working wit h I m ages Sect ion 4.8. Transform at ions Chapt er 5. Text Handling

Sect ion 5.1. Text Syst em Archit ect ure

Sect ion 5.2. Assem bling t he Text Syst em

  Chapt er 6. Net working Sect ion 6.1. Host s Sect ion 6.2. URL Resources Sect ion 6.3. Rendezvous Net work Services Sect ion 6.4. Socket s Sect ion 6.5. NSFileHandle

  

Chapt er 7. I nt erapplicat ion Com m unicat ion

Sect ion 7.1. NSPipe Chapt er 8. Ot her Fram eworks Sect ion 8.1. AddressBook

  

Sect ion 8.2. The Message Fram ework

Sect ion 8.3. Disc Recording Fram eworks

Sect ion 8.4. Third- Part y Fram eworks

  Part I I : API Quick Reference Chapt er 9. Foundat ion Types and Const ant s Sect ion 9.1. Dat a Types Sect ion 9.2. Enum erat ions Sect ion 9.3. Global Variables

  Sect ion 9.4. Const ant s Sect ion 9.5. Except ions Chapt er 10. Foundat ion Funct ions Sect ion 10.1. Assert ions

  Sect ion 10.2. Bundles Sect ion 10.3. Byt e Ordering Sect ion 10.4. Decim als Sect ion 10.5. Java Set up Sect ion 10.6. Hash Tables Sect ion 10.7. HFS File Types Sect ion 10.8. Map Tables Sect ion 10.9. Obj ect Allocat ion Sect ion 10.10. Obj ect ive- C Runt im e Sect ion 10.11. Pat h Ut ilit ies Sect ion 10.12. Point s Sect ion 10.13. Ranges Sect ion 10.14. Rect s Sect ion 10.15. Sizes Sect ion 10.16. Uncaught Except ions Sect ion 10.17. Zones

  

Chapt er 11. Applicat ion Kit Types and Const ant s

Sect ion 11.1. Dat a Types Sect ion 11.2. Enum erat ions Sect ion 11.3. Global Variables Sect ion 11.4. Except ions Chapt er 12. Applicat ion Kit Funct ions Sect ion 12.1. Accessibilit y Sect ion 12.2. Applicat ions Sect ion 12.3. Event s Sect ion 12.4. Font s Sect ion 12.5. Graphics: General Sect ion 12.6. Graphics: Window Dept h Sect ion 12.7. I nt erface St yles Sect ion 12.8. OpenGL Sect ion 12.9. Panels Sect ion 12.10. Past eboards Sect ion 12.11. Syst em Beep Chapt er 13. Foundat ion Classes NSAppleEventDescriptor NSAppleEventManager NSAppleScript NSArchiver NSArray NSAssertionHandler NSAttributedString NSAutoreleasePool NSBundle NSCalendarDat e NSCharacterSet NSClassDescription

  NSCloneCom m and NSCloseCom m and NSCoder NSConditionLock NSConnect ion NSCountCom m and NSCountedSet NSCreateCom m and NSData NSDate NSDateForm atter NSDecim alNum ber NSDecim alNum berHandler NSDeleteCom m and NSDeserializer NSDict ionary NSDirectoryEnum erator NSDistantObj ect NSDistantObj ectRequest NSDist ribut edLock

NSDistributedNotificationCenter

NSEnum erator NSExcept ion NSExistsCom m and NSFileHandle NSFileManager NSForm atter NSGetCom m and NSHost NSI ndexSpecifier NSI nvocat ion NSKeyedArchiver NSKeyedUnarchiver NSLock NSLogicalTest NSMachBootstrapServer NSMachPort NSMessagePort NSMessagePortNam eServer NSMethodSignature NSMiddleSpecifier NSMoveCom m and NSMutableArray NSMutableAttributedString NSMutableCharacterSet NSMutableData NSMutableDictionary NSMutableSet NSMut ableSt ring NSNam eSpecifier NSNetService NSNetServiceBrowser NSNot ificat ion

  NSNotificationCenter NSNotificationQueue NSNull NSNum ber NSNum berForm atter NSObject NSPipe NSPort NSPortCoder NSPortMessage NSPortNam eServer NSPositionalSpecifier NSProcessI nfo

NSPropertyListSerialization

NSPropert ySpecifier NSProtocolChecker NSProxy NSQuitCom m and NSRandom Specifier NSRangeSpecifier NSRecursiveLock NSRelat iveSpecifier NSRunLoop NSScanner NSScriptClassDescription NSScriptCoercionHandler NSScriptCom m and

NSScriptCom m andDescription

NSScriptExecutionContext NSScriptObj ectSpecifier NSScriptSuiteRegistry NSScriptWhoseTest NSSerializer NSSet NSSetCom m and NSSocketPort NSSocketPortNam eServer NSSpecifierTest NSSpellServer NSString NSTask NSThread NSTim er NSTim eZone NSUnarchiver NSUndoManager NSUniqueI DSpecifier NSURL NSURLHandle NSUserDefault s NSValue NSWhoseSpecifier

  

Chapt er 14. Foundat ion Prot ocols

  NSCoding NSCom parisonMethods NSCopying

NSDecim alNum berBehaviors

NSKeyValueCoding NSLocking NSMut ableCopying NSObj CTypeSerializat ionCallBack NSObject

NSScriptingCom parisonMethods

NSScriptKeyValueCoding NSScriptObj ectSpecifiers NSURLHandleClient

Chapt er 15. Applicat ion Kit Classes

NSAct ionCell NSAffineTransform NSApplicat ion NSBezierPath NSBitm apI m ageRep NSBox NSBrowser NSBrowserCell NSButton NSBut t onCell NSCachedI m ageRep NSCell NSClipView NSColor NSColorList NSColorPanel NSColorPicker NSColorWell NSCom boBox NSCom boBoxCell NSControl NSCursor NSCustom I m ageRep NSDocum ent NSDocum entController NSDrawer NSEPSI m ageRep NSEvent NSFileWrapper NSFont NSFontManager NSFont Panel NSForm NSForm Cell NSGlyphI nfo NSGraphicsContext NSHelpManager NSI m age NSI m ageCell

  NSI m ageRep NSI m ageView NSI nputManager NSI nputServer NSLayoutManager NSMatrix NSMenu NSMenuI tem NSMenuI tem Cell NSMenuView NSMovie NSMovieView NSMutableParagraphStyle NSNibConnector NSNibControlConnector NSNibOutletConnector NSOpenGLContext NSOpenGLPixelForm at NSOpenGLView NSOpenPanel NSOut lineView NSPageLayout NSPanel NSParagraphStyle NSPasteboard NSPDFI m ageRep NSPI CTI m ageRep NSPopUpButton NSPopUpButtonCell NSPrinter NSPrintI nfo NSPrintOperation NSPrintPanel NSProgressI ndicator NSQuickDrawView NSResponder NSRulerMarker NSRulerView NSSavePanel NSScreen NSScroller NSScrollView NSSecureText Field NSSecureTextFieldCell

NSSim pleHorizontalTypesetter

NSSlider NSSliderCell NSSound NSSpellChecker NSSplitView NSStatusBar NSStatusI tem NSStepper

  NSSt epperCell NSTableColum n NSTableHeaderCell NSTableHeaderView NSTableView NSTabView NSTabViewI t em NSText NSTextAttachm ent NSTextAttachm entCell NSTextContainer NSText Field NSText FieldCell NSTextStorage NSTextTab NSText View NSToolbar NSToolbarI tem NSTypesetter NSView NSWindow NSWindowCont roller NSWorkspace

Chapt er 16. Applicat ion Kit Prot ocols

NSAccessibilit y NSChangeSpelling NSColorPickingCustom NSColorPickingDefault NSCom boBoxCellDataSource NSCom boBoxDataSource NSDraggingDestination NSDraggingI nfo NSDraggingSource NSI gnoreMisspelledWords NSI nputServerMouseTracker NSI nputServiceProvider NSMenuI tem NSMenuValidation NSNibAwaking NSOutlineViewDataSource NSServicesRequests NSTableDataSource NSTextAttachm entCell NSText I nput NSTextStorageScripting NSToolbarI t em Validat ion NSToolTipOwner NSUserI nterfaceValidations

NSValidatedUserI nterfaceI tem

NSWindowScript ing

  Met hod I ndex A

  B C D E F G H

  I J K L M N O P Q R S T U

  V W

  XYZ

  Part I I I : Appendix Appendix A. Appendix: Resources for Cocoa Developers Sect ion A.1. Apple Docum ent at ion Sect ion A.2. Relat ed Books Sect ion A.3. Web Sit es Sect ion A.4. Mailing List s Sect ion A.5. Part nering wit h Apple Colophon I ndex [ Team LiB ]

  [ Team LiB ] Copyright © 2003 O'Reilly & Associat es, I nc.

  Print ed in t he Unit ed St at es of Am erica. Published by O'Reilly & Associat es, I nc., 1005 Gravenst ein Highway Nort h, Sebast opol, CA 95472. O'Reilly & Associat es books m ay be purchased for educat ional, business, or sales prom ot ional use. Online edit ions are also available for m ost t it les ( . For m ore inform at ion, cont act our corporat e/ inst it ut ional sales depart m ent : ( 800) 998- 9938 or corporate@oreilly.com .

  Nut shell Handbook, t he Nut shell Handbook logo, and t he O'Reilly logo are regist ered t radem arks of O'Reilly & Associat es, I nc. Many of t he designat ions used by m anufact urers and sellers t o dist inguish

t heir product s are claim ed as t radem arks. Where t hose designat ions appear in t his book, and O'Reilly

& Associat es, I nc. was aware of a t radem ark claim , t he designat ions have been print ed in caps or

init ial caps. The associat ion bet ween t he im age of an I rish set t er and t he t opic of Cocoa is a t radem ark

of O'Reilly & Associat es, I nc.

  Apple Com put er, I nc. boldly com bined open source t echnologies wit h it s own program m ing effort s t o creat e Mac OS X, one of t he m ost versat ile and st able operat ing syst em s now available. I n t he sam e spirit , Apple has j oined forces wit h O'Reilly & Associat es t o bring you an indispensable collect ion of t echnical publicat ions. The ADC logo indicat es t hat t he book has been t echnically reviewed by Apple engineers and is recom m ended by t he Apple Developer Connect ion. Apple, t he Apple logo, AppleScript , AppleTalk, AppleWorks, Carbon, Cocoa, ColorSync, Finder, FireWire, iBook, iMac, iPod, Mac, Mac logo, Macint osh, PowerBook, QuickTim e, QuickTim e logo, Sherlock, and WebObj ect s are t radem arks of Apple Com put er, I nc., regist ered in t he Unit ed St at es and ot her count ries. The "keyboard" Apple logo ( ) is used wit h perm ission of Apple Com put er, I nc.

  While every precaut ion has been t aken in t he preparat ion of t his book, t he publisher and aut hors assum e no responsibilit y for errors or om issions, or for dam ages result ing from t he use of t he inform at ion cont ained herein.

  [ Team LiB ]

  [ Team LiB ] Preface I t 's pract ically im possible t o know Cocoa inside and out . There was once a discussion bet ween t wo program m ers about Cocoa's large API s: one was a vet eran Perl program m er, t he ot her a Cocoa program m er. The Perl program m er grum bled about t he int im idat ing and verbose Cocoa API s, saying t here was sim ply t oo m uch t o rem em ber. Bem used, t he Cocoa program m er ret ort ed: "You don't rem em ber Cocoa; you look it up! " The point t he Cocoa program m er was t rying t o im press upon t he Perl program m er was t hat

understanding obj ect - orient ed program m ing ( OOP) concept s and t he archit ect ure of t he fram eworks is

m ore im port ant t han rem em bering t he wordy and num erous m et hod and class nam es in t he Cocoa fram eworks. This book is a com pact reference t hat will hopefully grow worn beside your keyboard. Split int o t wo

parts, Cocoa in a Nut shell first provides an overview of t he fram eworks t hat focuses on bot h com m on

program m ing t asks and how t he part s of t he fram ework int eract wit h one anot her. The second part of

t he book is an API quick reference t hat frees you from having t o rem em ber m et hod and class nam es

so you can spend m ore t im e hacking code. This book covers t he Cocoa fram eworks—Foundat ion and Applicat ion Kit ( AppKit ) —as of Mac OS X 10.2 ( Jaguar) .

  [ Team LiB ]

  [ Team LiB ] What Is Cocoa?

Cocoa is a com plet e set of classes and applicat ion program m ing int erfaces ( API s) for building Mac OS

X applicat ions and t ools. Wit h over 240 classes, Cocoa is divided int o t wo essent ial fram eworks: t he Foundat ion fram ework and t he Applicat ion Kit . The Foundat ion fram ework provides a fundam ent al set of t ools for represent ing fundam ent al dat a t ypes, accessing operat ing syst em services, t hreading, m essaging, and m ore. The Applicat ion Kit provides t he funct ionalit y t o build graphical user int erfaces ( GUI ) for Cocoa applicat ions. I t provides

access t o t he st andard Aqua int erface com ponent s ranging from m enus, but t ons, and t ext fields—t he

building blocks of larger int erfaces—t o com plet e, prepackaged int erfaces for print dialogs, file operat ion dialogs, and alert dialogs. The Applicat ion Kit also provides higher- level funct ionalit y t o im plem ent m ult iple docum ent applicat ions, t ext handling, and graphics. Classes are not t he only const it uent s of t he Cocoa fram eworks. Som e program m ing t asks, such as

sounding a syst em beep, are best accom plished wit h a sim ple C funct ion. Cocoa includes a num ber of

funct ions for accom plishing t asks such as m anipulat ing byt e orders and drawing sim ple graphics. Addit ionally, Cocoa defines a num ber of cust om dat a t ypes and const ant s t o provide a higher degree of abst ract ion t o m any m et hod param et ers.

  The Cocoa Development Environment Proj ect Builder and I nt erface Builder are t he t wo m ost im port ant applicat ions used in Cocoa

developm ent. Proj ect Builder is t he int eract ive developm ent environm ent ( I DE) for Mac OS X used t o

m anage and edit source files, libraries, fram eworks, and resources. Addit ionally, it provides an int erface t o t he Obj ect ive- C com piler, gcc, and t he GNU debugger, gdb.

  

I nt erface Builder is used t o creat e GUI s for Cocoa applicat ions by allow ing developers t o m anipulat e UI

com ponent s ( such as windows and but t ons) graphically using drag and drop. I t provides assist ance for

laying out com ponent s by providing visual cues t hat conform t o Apple's Aqua Hum an I nt erface Guidelines. From an inspect or panel, t he behavior and appearance of t hese com ponent s can be t weaked in alm ost every way t he com ponent support s. I nt erface Builder provides an int uit ive way t o connect obj ect s by let t ing t he user drag wires bet ween obj ect s. This way, you set up t he init ial

net work of obj ect s in t he int erface. I n addit ion, you can int erface wit hout having t o com pile a single bit

of code.

  

I nt erface com ponent s are not t he only obj ect s t hat can be m anipulat ed wit h I nt erface Builder. You can

subclass any Cocoa class and creat e inst ances of t he subclasses. More im port ant ly, you can give t hese

classes inst ance variables, known as out let s, and m et hods, called act ions, and hook t hem up t o user int erface com ponent s. I nt erface Builder can t hen creat e source files for t hese subclasses, com plet e

header files, and an im plem ent at ion file including st ubs for t he act ion m et hods. There is m uch m ore t o

I nt erface Builder and Proj ect Builder t han we can cover in t his book, but as you can begin t o im agine,

t he t ight int egrat ion of t hese t wo applicat ions creat e a com pelling applicat ion developm ent environm ent .

  Cocoa Design Patterns Cocoa uses m any design pat t erns. Design pat t erns are descript ions of com m on obj ect - orient ed program m ing pract ices. Effect ive applicat ion developm ent requires t hat you know how and where t o use pat t erns in Cocoa. Cocoa in a Nut shell discusses t hese pat t erns in t he cont ext in which t hey are used. Here is a brief list of t he design pat t erns you will encount er in t he book:

  Delegat ion I n t his pat t ern, one obj ect , t he delegat e, act s on behalf of anot her obj ect . Delegat ion is used t o alt er t he behavior of an obj ect t hat t akes a delegat e. The developer's j ob is t o im plem ent any

num ber of m et hods t hat m ay be invoked in t he delegat e. Delegat ion m inim izes t he need t o

subclass obj ect s t o ext end t heir funct ionalit y.

  Singlet on This pat t ern ensures t hat only one obj ect inst ance of a class exist s in t he syst em . A singleton m et hod is an obj ect const ruct or t hat creat es an inst ance of t he class and m aint ains a reference t o t hat obj ect . Subsequent invocat ions of t he singlet on const ruct or ret urn t he exist ing obj ect , rat her t han creat e a new one.

  Not ificat ion

Not ificat ions allow decoupling of m essage senders from m ult iple m essage receivers. Cocoa

im plem ent s t his pat t ern in t he not ificat ion syst em used t hroughout t he fram eworks. I t is

discussed in Chapt er 2 .

  Model- View - Cont rol The Model- View- Cont roller ( MVC) pat t ern is used ext ensively in t he Applicat ion Kit t o separat e an applicat ion int o logically dist inct unit s: a m odel, which knows how t o work wit h applicat ion

dat a, t he view, which is responsible for present ing t he dat a t o t he user, and t he cont roller,

which handles int eract ion bet ween t he m odel and t he view. Chapt er 3 discusses MVC in m ore detail.

  Target / act ion

The t arget / act ion pat t ern decouples user- int erface com ponent s, such as but t ons and m enu

it em s, wit h t he obj ect s ( t he t arget s) t hat im plem ent t heir act ions. I n t his pat t ern, an act ivat ed cont rol sends an act ion m essage t o it s t arget . Chapt er 3 discusses t his t opic furt her.

  Responder chain

The responder chain pat t ern is used in t he event handling syst em t o give m ult iple obj ect s a

chance t o respond t o an event . This t opic is discussed in Chapt er 3 .

  Key- value coding Key- value coding provides an int erface for accessing an obj ect 's propert ies indirect ly by nam e.

  Chapt er 2 covers key- value coding m ore t horoughly.

  Benefits These days, applicat ion developers expect a lot from t heir t ools, and users expect a lot from any applicat ion t hey use. Any applicat ion or applicat ion t oolkit t hat neglect s t hese needs is dest ined for

failure. Cocoa com es t hrough grandly by providing t he feat ures needed in applicat ions now and in t he

fut ure, including: Fram ew ork- based developm ent

  Cocoa developm ent is based on it s fram eworks: t he Foundat ion fram ework and t he Applicat ion

Kit . Wit h fram ework- based program m ing, t he syst em t akes a cent ral role in t he life of an

applicat ion by calling out t o code t hat you provide. This role allows t he fram eworks t o t ake care of an applicat ion's behind- t he- scene det ails and let s you focus on providing t he funct ionalit y t hat m akes your applicat ion unique.

  " For free" feat ures Cocoa provides a lot of st andard applicat ion funct ionalit y "for free" as part of t he fram eworks.

  

These feat ures not only include t he large num ber of user- int erface com ponent s, but larger

applicat ion subsyst em s such as t he t ext - handling syst em and t he docum ent - based applicat ion

archit ect ure. Because Apple has gone t o great lengt hs t o provide t hese feat ures as a part of

Cocoa, developers can spend less t im e doing t he repet it ive work t hat is com m on bet ween all

applicat ions, and m ore t im e adding unique value t o t heir applicat ion.

  The developm ent environm ent As discussed earlier, Proj ect Builder and I nt erface Builder provide a developm ent environm ent t hat is highly int egrat ed wit h t he Cocoa fram eworks. I nt erface Builder is used t o quickly build user int erfaces, which m eans less t edious work for t he developer. Cocoa's m ost im port ant benefit is t hat it let s you develop applicat ions dram at ically fast er t han wit h ot her applicat ion fram eworks.

  Languages Cocoa's nat ive language is Obj ect ive- C. The Foundat ion and Applicat ion Kit fram eworks are

im plem ent ed in Obj ect ive- C, and using Obj ect ive- C provides access t o all feat ures of t he fram eworks.

  Chapt er 1 covers Obj ect ive- C in dept h.

  

Obj ect ive- C is not , however, t he only language t hrough which you can access t he Cocoa fram eworks.

Through t he Java Bridge, Apple provides a way t o access t he Cocoa fram eworks using t he Java language. The Java Bridge does not provide a com plet e solut ion since m any of Cocoa's advanced

feat ures, such as t he dist ribut ed obj ect s syst em , are not available wit h Java. This book will not discuss

Cocoa applicat ion developm ent wit h Java.

  Anot her opt ion for working wit h Cocoa is AppleScript . AppleScript has t radit ionally been associat ed wit h sim ple script ing t asks, but wit h Mac OS X, Apple enabled AppleScript access t o t he Cocoa

fram eworks via AppleScript St udio. AppleScript St udio provides hooks int o t he Cocoa API so script ers

can t ake t heir exist ing knowledge of AppleScript , writ e an applicat ion in Proj ect Builder, and use

I nt erface Builder t o give t heir applicat ions an Aqua int erface—all wit hout having t o learn Obj ect ive- C.

This exposes Cocoa t o a com plet ely new base of Macint osh developers, who know enough AppleScript

t o build sim ple t ask- driven applicat ions for solving com m on problem s. For m ore inform at ion about AppleScript St udio, see .

  [ Team LiB ]

  [ Team LiB ] How This Book Is Organized

This book is split int o t wo part s: t he overview of Cocoa fam iliarizes developers wit h Cocoa's st ruct ure,

and t he API quick reference cont ains m et hod nam e list ings and brief descript ions for all Foundat ion and Applicat ion Kit fram ework classes.

  Part I is divided int o t he following eight chapt ers: Chapt er 1 , Obj ect ive- C This chapt er int roduces t he use of Obj ect ive- C language. Many obj ect - orient ed concept s you m ay be fam iliar wit h from ot her languages are discussed in t he cont ext of Obj ect ive- C, which let s you leverage your previous knowledge.

  Chapt er 2 , Foundat ion This chapt er discusses t he Foundat ion fram ework classes t hat all program s require for com m on program m ing t asks such as dat a handling, process cont rol, run loop m anagem ent , and int erapplicat ion com m unicat ion.

  Chapt er 3 , The Applicat ion Kit This chapt er int roduces t he Applicat ion Kit and det ails larger abst ract ions of t he Applicat ion Kit ,

such as how event s are handled wit h responder chains, t he docum ent - based applicat ion

archit ect ure, and ot her design pat t erns t hat are im port ant in Cocoa developm ent .

  Chapt er 4 , Draw ing and I m aging

This chapt er discusses Cocoa's t wo- dim ensional ( 2D) graphics capabilit ies available in t he

Applicat ion Kit .

  Chapt er 5 , Text Handling This chapt er det ails t he archit ect ure of Cocoa's advanced t ext - handling syst em , which provides a rich level of t ext - handling funct ionalit y for all Cocoa developers.

  Chapt er 6 , Net w orking This chapt er sum m arizes net working t echnologies, such as Rendezvous and URL services, t hat are accessible from a Cocoa applicat ion.

  Chapt er 7 , I nt erapplicat ion Com m unicat ion This chapt er discusses int erapplicat ion com m unicat ion t echniques, including dist ribut ed obj ect s, pipes, and dist ribut ed not ificat ions.

  Chapt er 8 , Ot her Fram ew orks This chapt er provides inform at ion about t he m any Obj ect ive- C fram eworks t hat can be used in conj unct ion wit h Cocoa. These fram eworks include t hose t hat are part of Mac OS X, such as

AddressBook and DiscRecording, as well as fram eworks supplied by t hird- part y developers.

  

Part I I cont ains Foundat ion and AppKit fram ework references and, as such, m akes up t he bulk of t he

book. First , t here's an explanat ion of t he organizat ion of chapt ers in

  Part I I and how class inform at ion

is referenced. The rest of t he sect ion is divided int o eight chapt ers and a m et hod index. Each chapt er

focuses on a different part of t he Cocoa API .

  Chapt er 9 , Foundat ion Types and Const ant s This chapt er list s t he dat a t ypes and const ant s defined by t he Foundat ion fram ework. Chapt er 10 , Foundat ion Funct ions This chapt er list s t he funct ions defined by t he Foundat ion fram ework. Chapt er 11 , Applicat ion Kit Types and Const ant s

  This chapt er list s t he dat a t ypes and const ant s defined by t he Applicat ion Kit .

  Chapt er 12 , Applicat ion Kit Funct ions This chapt er list s t he funct ions defined by t he Applicat ion Kit . Chapt er 13 , Foundat ion Classes This chapt er cont ains t he API quick- reference Foundat ion fram ework classes. Chapt er 14 , Foundat ion Prot ocols

  This sm aller chapt er covers t he handful of prot ocols declared as part of t he Foundat ion fram ework.

  Chapt er 15 , Applicat ion Kit Classes This chapt er provides t he API quick reference for Applicat ion Kit classes. Chapt er 16 , Applicat ion Kit Prot ocols This chapt er provides reference t o t he prot ocols defined and used in t he AppKit . Chapt er 17 , Met hod I ndex

  This index cont ains an alphabet ical list ing of every m et hod in t he Foundat ion fram ework and

Applicat ion Kit . Each m et hod nam e in t he index has a list of classes t hat im plem ent t hat

m et hod. Unlike t he rest of t he book's sect ions, t here is but one short appendix in

  Part I I I . Regardless of your

experience level as a Mac developer, t his sect ion cont ains valuable resources for Cocoa program m ers,

including det ails on how you can part ner wit h Apple t o m arket your applicat ion.

  Appendix A This appendix list s vit al resources for Cocoa developers, including Apple developer docum ent at ion, web sit es, m ailing list s, books, and det ails on how t o part ner wit h Apple t o gain exposure for your applicat ions.

  [ Team LiB ]

  [ Team LiB ] Conventions Used in This Book This book uses t he following t ypographical convent ions: I t alic

  Used t o indicat e new t erm s, URLs, filenam es, file ext ensions, direct ories, com m ands, opt ions, and program nam es, and t o highlight com m ent s in exam ples. For exam ple, a filesyst em pat h will appear as / Applications/ Utilities.

  Constant width Used t o show t he cont ent s of files or out put from com m ands.

  Constant-width bold Used in exam ples and t ables t o show com m ands or ot her t ext t hat t he user should t ype lit erally.

  Constant-width italic Used in exam ples and t ables t o show t ext t hat should be replaced wit h user- supplied values, and also t o highlight com m ent s in code.

  Menus/ navigat ion Menus and t heir opt ions are referred t o in t he t ext as File Open, Edit Copy, et c. Arrows will also signify a navigat ion pat h in window opt ions—for exam ple, Syst em Preferences

Screen Effect s Act ivat ion m eans t hat you would launch Syst em Preferences, click on t he

icon for t he Screen Effect s preferences panel, and select t he Act ivat ion pane wit hin t hat panel.

  Pat hnam es Pat hnam es show t he locat ion of a file or applicat ion in t he filesyst em . Direct ories ( or folders for Mac and Windows users) are separat ed by a forward slash. For exam ple, if you see som et hing like, "...launch t he Term inal applicat ion ( / Applications/ Utilities) " in t he t ext , you'll know t hat t he Term inal applicat ion can be found in t he Ut ilit ies subfolder of t he Applicat ions folder.

  % , #

  The percent sign ( % ) shows t he user prom pt for t he default t csh shell; t he hash m ark ( # ) is t he prom pt for t he root user.

  Menu sym bols When looking at t he m enus for any applicat ion, you will see sym bols associat ed wit h keyboard short cut s for a part icular com m and. For exam ple, t o open a docum ent in Microsoft Word, go t o t he File m enu and select Open ( File Open) , or issue t he keyboard short cut , - O.

  Figure P- 1 shows t he sym bols used in various m enus t o denot e a short cut .

  

Figu r e P- 1 . Ke yboa r d a cce le r a t or s for issu in g com m a n ds

You'll rarely see t he Cont rol sym bol used as a m enu com m and opt ion; it 's m ore oft en used in associat ion wit h m ouse clicks or for working wit h t he t csh shell.

  I ndicat es a t ip, suggest ion, or general not e.

  I ndicat es a warning or caut ion.

  [ Team LiB ]

  [ Team LiB ] How the Quick Reference Was Generated You'd have t o be a m adm an t o writ e t his book's quick reference by hand. Madm en we are not , so

following t he exam ple of David Flanagan, aut hor of O'Reilly's Java in a Nut shell, Mike wrot e a program

t hat would t ake care of m ost of t he t edious work.

The idea is t o at t ack t he problem in t wo st ages. I n t he first st age, t he code enum erat es each header

file of each Fram ework t hat is t o be ripped ( Foundat ion and AppKit ) and runs each line of each header

t hrough a parser. This parser would look for key elem ent s t hat ident ify part s of t he header, such as

  • @interface

  , for class m et hods, for inst ance m et hods, and so fort h. Every discovered elem ent was

assem bled int o a cross- linked hierarchy of fram ework nam es, class nam es, or m et hod nam es. When

all headers had been processed, t he hierarchy was out put int o a propert y list file, which, at t he end of

t he day, weighed in at j ust over 41,500 lines of t ext !

St age t wo involved reading t he cont ent s of t his file and running it t hrough several form at t ing rout ines

t hat out put t he XML- form at t ed t ext required by t he O'Reilly product ion t eam .

  

Each class has a lit t le class hierarchy figure. These figures were aut ogenerat ed by drawing int o a view

( using NSBezierPath ) and saving t he PDF represent at ion of t he view cont ent s t o a file. The input dat a

for t he program t hat did all of t he drawing was t he sam e propert y list used t o creat e t he API quick reference ent ries.

  [ Team LiB ]

  [ Team LiB ] Comments and Questions Please address com m ent s and quest ions concerning t his book t o t he publisher: O'Reilly & Associat es, I nc.

  1005 Gravenst ein Highway Nort h Sebast opol, CA 95472 800- 998- 9938 ( in t he Unit ed St at es or Canada) 707- 829- 0515 ( int ernat ional or local) 707- 829- 0104 ( fax)

There is a web page for t his book, which list s errat a, exam ples, or any addit ional inform at ion. You can

access t his page at :

  To com m ent or ask t echnical quest ions about t his book, send em ail t o: bookquestions@oreilly.com

  

For m ore inform at ion about books, conferences, Resource Cent ers, and t he O'Reilly Net work, see t he

O'Reilly web sit e at :

  [ Team LiB ]

  [ Team LiB ] Acknowledgments The aut hors would like t o acknowledge t he m any people who helped m ake t his book possible. From Mike Writ ing t his book has been quit e an experience, and it was m ade possible only by t he effort s and support of t he people I worked wit h. My edit or, Chuck Toporek, put in a lot of t im e on t his book and kept t his first - t im e aut hor on course and in t he right fram e of m ind wit h his kind words of

encouragem ent and level- headed advice. He has becom e a good friend over t he past year t hat we've

worked t oget her on t his proj ect . I am grat eful t o Duncan for his effort s in helping m e shape up t he book and for cont ribut ing t he m at erial on Obj ect ive- C. Duncan is quit e a person t o work wit h, and I look forward t o working wit h him on t his book in t he fut ure. Any success of t his book is due in no sm all part t o bot h Chuck and Duncan. These t wo m ake a great t eam , and I am fort unat e t o have t he opport unit y t o work wit h t hem .

Thanks t o t he t ech reviewers: Scot t Anguish, Sherm Pendley, and t he engineers and t echnical writ ers

at Apple who were kind enough t o t ake t im e out of t heir busy lives t o review t he book. Special t hanks

go t o Malcolm Crawford for going above and beyond t he call of dut y by providing in- dept h com m ent s

and suggest ions and working closely wit h us t o give t he book it s final polish. His upbeat at t it ude and Brit ish charm helped us all bring t his book t o com plet ion. Derrick St ory at t he O'Reilly Net work t ook an am azing chance wit h m e by let t ing m e writ e about Cocoa for www.m acdevcenter.com , which gave m e t he opport unit y t o get m y foot in t he door when I was least expect ing it . Why he did t his baffles m e t o t his day, but I am grat eful for it and for his encouragem ent over t he past t wo years.

Ryan Dionne int roduced m e t o Macs when we were freshm an at UT Aust in, and he quickly changed m y

at t it ude about t hem ( I was a swit cher before swit ching was fashionable) . Short ly aft er t hat , John Ket o

of t he Universit y of Texas, m y t eacher and em ployer, was t ricked, by som e of t he grad st udent s I worked wit h, int o believing t hat I was som e sort of Linux and C guru; let 's j ust say t hat I quickly becam e one! I suppose t hat if eit her of t hese t hings hadn't happened, you wouldn't be reading t his acknowledgm ent . Life's funny som et im es. All rem aining t hanks, and all t hat I am , go t o m y fam ily and m y friends: Mom and Dad, for t he love,

encouragem ent , and support during t he whole process; m y sist ers Krist in and Jennifer; and m y fut ure

parent s- in- law, Bill and Lauren, for t heir love and support ; Ryan, Paige, and Tom m y for put t ing up wit h m e and m y ant isocial behaviors during t he past year, and for always having an eye on m e and knowing when I needed t o get som e lunch. As always, m y love and appreciat ion t o m y fiancée, Heat her, ( unt il July 2003! ) for being incredibly pat ient , support ive, and caring during t he past year.

  From Duncan

I 'd like t o t hank Mike and Chuck for let t ing m e cont ribut e Chapt er 1 t o t he book. They were bot h very

pat ient and at t ent ive t o all of t he feedback I cont ribut ed t o t he rest of t he book, even when t hey m ust

have becom e annoyed by all m y suggest ions. Chuck, you're a great edit or and you've helped m e

develop as an aut hor, a skill t hat I never t hought I 'd have. Mike, I 'm honored t o have helped you wit h

t his book, and I look forward t o working wit h you on it again in t he fut ure.

m m alcolm Crawford provided an invaluable service by checking t he Obj ect ive- C chapt er, as well as t he

  

discussions, and plent y of red ink st em m ing from m any years of experience, have illum inat ed several

areas of Cocoa and Obj ect ive- C for m e. This book would not be t he book it is wit hout his valuable help. Finally, t hanks t o m y fam ily and friends who put up wit h m e disappearing during t he crunch t im e leading up t o t he product ion of t his book. You guys know who you are.

  [ Team LiB ]

  [ Team LiB ]

  Part I: Introducing Cocoa This part of t he book provides a series of chapt ers t hat provide a general overview of Cocoa,

helping you t o quickly com e up t o speed. The chapt ers in t his part of t he book include:

Chapt er 1 , Obj ect ive- C Chapt er 2 , Foundat ion Chapt er 3 , The Applicat ion Kit Chapt er 4 , Draw ing and I m aging Chapt er 5 , Text Handling Chapt er 6 , Net w orking Chapt er 7 , I nt erapplicat ion Com m unicat ion Chapt er 8 , Ot her Fram ew orks

  [ Team LiB ]

  [ Team LiB ]

Chapter 1. Objective-C Obj ect ive- C is a highly dynam ic, m essage- based obj ect- oriented language. Consist ing of a sm all

  num ber of addit ions t o ANSI C, Obj ect ive- C is charact erized by it s deferral of m any decisions unt il

runt im e, support ing it s key feat ures of dynam ic dispat ch, dynam ic t yping, and dynam ic loading. These

feat ures support m any of t he design pat t erns Cocoa uses, including delegat ion, not ificat ion, and

Model- View- Cont roller ( MVC) . Because it is an ext ension of C, exist ing C code and libraries, including

  [ 1] t hose based on C+ + , can work wit h Cocoa- based applicat ions wit hout losing any of t he effort t hat went int o t heir original developm ent .

  [ 1] For m ore inform at ion on using C+ + wit h Obj ect ive- C, see t he Obj ect ive- C+ + docum ent at ion cont ained in / Developer/ Docum ent at ion/ ReleaseNot es/ Obj ect ive- C+ + .ht m l.

  This chapt er is an overview of Obj ect ive- C's m ost frequent ly used feat ures. I f you need m ore det ail about t hese feat ures or want t o see t he full language specificat ion, read t hrough Apple's docum ent , The Obj ect ive- C Program m ing Language, w hich is inst alled as part of t he Developer Tools in / Developer/ Docum ent at ion/ Cocoa/ Obj ect iveC.

  [ Team LiB ]

  [ Team LiB ]

1.1 Objects

  

The base unit of act ivit y in all obj ect - orient ed languages is t he obj ect —an ent it y t hat associat es dat a

wit h operat ions t hat can be perform ed on t hat dat a. Obj ect ive- C provides a dist inct dat a t ype, id , defined as a point er t o an obj ect 's dat a t hat allows you t o work wit h obj ect s. An obj ect m ay be declared in code as follows:

  id anObject;

  For all obj ect - orient ed const ruct s of Obj ect ive- C, including m et hod ret urn values, id replaces t he default C int as t he default ret urn dat a t ype.

  1.1.1 Dynamic Typing

The id t ype is com plet ely nonrest rict ive. I t says very lit t le about an obj ect , indicat ing only t hat it is an

ent it y in t he syst em t hat can respond t o m essages and be queried for it s behavior. This t ype of behavior, known as dynam ic t yping, allows t he syst em t o find t he class t o which t he obj ect belongs and resolve m essages int o m et hod calls.

  1.1.2 Static Typing

Obj ect ive- C also support s st at ic t yping, in which you declare a variable using a point er t o it s class t ype

inst ead of id , for exam ple:

  NSObject *object;

  

This declarat ion will t urn on som e degree of com pile t im e checking t o generat e warnings when a t ype

m ism at ch is m ade, as well as when you use m et hods not im plem ent ed by a class. St at ic t yping can

also clarify your int ent ions t o ot her developers who have access t o your source code. However, unlike

ot her languages' use of t he t erm , st at ic t yping in Obj ect ive- C is used only at com pile t im e. At runt im e,

all obj ect s are t reat ed as t ype id t o preserve dynam ism in t he syst em .

  There are no class- cast except ions like t hose present in m ore st rongly t yped

  Dog Cat

  languages, such as Java. I f a variable declared as a t urns out t o be a , but responds t o t he m essages called on it at runt im e, t hen t he runt im e won't com plain.

  [ Team LiB ]

  [ Team LiB ]

1.2 Messaging

  

Obj ect s in Obj ect ive- C are largely aut onom ous, self- cont ained, opaque ent it ies wit hin t he scope of a

program . They are not passive cont ainers for st at e behavior, nor dat a and a collect ion of funct ions t hat can be applied t o t hat dat a. The Obj ect ive- C language reinforces t his concept by allowing any m essage—a request t o perform a part icular act ion—t o be passed t o any obj ect . The obj ect is t hen expect ed t o respond at runt im e wit h appropriat e behavior. I n obj ect - orient ed t erm inology, t his is called dynam ic binding.

  When an obj ect receives a m essage at runt im e, it can do one of t hree t hings: Perform t he funct ionalit y request ed, if it knows how.

  Forward t he m essage t o som e ot her obj ect t hat m ight know how t o perform t he act ion.

Em it a warning ( usually st opping program execut ion) , st at ing t hat it doesn't know how t o

respond t o t he m essage.

  A key feat ure here is t hat an obj ect can forward m essages t hat it doesn't know how t o deal wit h t o

ot her obj ect s. This feat ure is one of t he significant differences bet ween Obj ect ive- C and ot her obj ect -

orient ed languages such as Java and C+ + .

Dynam ic binding, as im plem ent ed in Obj ect ive- C, is different t han t he lat e binding provided by Java

and C+ + . While t he lat e binding provided by t hose languages does provide flexibilit y, it com es wit h st rict com pile- t im e const raint s and is enforced at link t im e. I n Obj ect ive- C, binding is perform ed as m essages are resolved t o m et hods and is free from const raint s unt il t hat t im e.

1.2.1 Structure of a Message

  [ 2] Message expressions in Obj ect ive- C are enclosed in square bracket s.

  [ 2] This convent ion is known as infix synt ax; it is borrowed from Sm allt alk.

  

The expression consist s of t he following part s: t he obj ect t o which t he m essage is sent ( t he receiver) ,

t he m essage nam e, and opt ionally any argum ent s. For exam ple, t he following m essage can be verbalized as "send a play m essage t o t he obj ect ident ified by t he iPod variable":

  [iPod play];