• Tidak ada hasil yang ditemukan

OReilly Cocoa In A Nutshell May 2003 ISBN 0596004621 pdf

N/A
N/A
Protected

Academic year: 2019

Membagikan "OReilly Cocoa In A Nutshell May 2003 ISBN 0596004621 pdf"

Copied!
1166
0
0

Teks penuh

(1)

[ 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

Published: May 2003 I SBN: 0- 596- 00462- 1 Pages: 566

Cocoa in a Nut shell begins wit 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 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 Kit fram eworks, based on t he Jaguar release ( Mac OS X 10.2) .

[ 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

Published: May 2003 I SBN: 0- 596- 00462- 1 Pages: 566

Cocoa in a Nut shell begins wit 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 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 Kit fram eworks, based on t he Jaguar release ( Mac OS X 10.2) .

(2)

[ 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

Published: May 2003 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

(3)

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

(4)

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

(5)

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

(6)

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

(7)

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

(8)

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

(9)

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

(10)

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

(11)

[ 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 (http: / / safari.oreilly.com) . 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.

(12)

[ 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) .

(13)

[ 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 allowing 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

(14)

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

(15)

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 http: / / www.apple.com / applescript/ studio.

(16)

[ 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

(17)

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.

(18)

[ 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 / Applicat ions/ Ut ilit ies.

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 (/ Applicat ions/ Ut ilit ies) " 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

(19)

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

I ndicat es a warning or caut ion.

(20)

[ 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.

(21)

[ 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 :

http: / / www.oreilly.com / catalog/ cocoaian

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 :

http: / / www.oreilly.com

(22)

[ 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.

(23)

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.

(24)

[ 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

(25)

[ Team LiB ]

Chapter 1. Objective-C

Obj ect ive- C is a highly dynam ic, m essage- based obj ect - orient ed 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 t hose based on C+ + ,[ 1] 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, which is inst alled as part of t he Developer Tools in

/ Developer/ Docum ent at ion/ Cocoa/ Obj ect iveC.

(26)

[ 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 languages, such as Java. I f a variable declared as a Dog t urns out t o be a Cat, 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.

(27)

[ 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

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

[ 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];

Any argum ent s in a m essage expression appear aft er colons in a m essage nam e. For exam ple, t o t ell the iPod obj ect t o set t he volum e, send it t he following m essage:

[iPod setVolume:11];

I f a m essage cont ains m ult iple argum ent s, t he argum ent s are t ypically separat ed in t he m essage nam e and follow colons aft er t he corresponding com ponent of t he m essage. For exam ple:

[iPod usePlaylist:@"Techno" shuffle:YES];

(28)

1.2.1.1 Nested messages

Messages can be nest ed so t he ret urn value from one m essage can becom e t he receiver or param et er for anot her. For exam ple, t o assign t he playlist for an iPod t o play t o t he value of an iTunes playlist nam e wit hout an int erm ediat e variable, use t he following:

[iPod usePlaylist:[iTunes currentPlaylist]];

1.2.1.2 Messaging nil

Messaging an uninit ialized ( or cleared) obj ect variable ( i.e., one wit h a value of nil) is not an error. I f a m essage doesn't have a ret urn value, not hing will happen. I f t he m essage ret urns an obj ect point er, it will ret urn nil. I f t he m essage ret urns a scalar value such as an int, it will ret urn 0. Ot herwise, t he ret urn value is unspecified.

1.2.2 How Messages Are Resolved into Methods

When a m essage is sent t o an obj ect , a search det erm ines t he im plem ent ed m et hod t hat should be called. The logic of t his search is:

The runt im e inspect s t he m essage's t arget obj ect t o det erm ine t he obj ect 's class. 1 .

I f t he class cont ains an inst ance m et hod wit h t he sam e nam e as t he m essage, t he m et hod is executed.

2 .

I f t he class does not have a m et hod, t he search is m oved t o t he superclass. I f a m et hod wit h t he sam e nam e as t he m essage is found in t he superclass, it is execut ed. This search is cont inued up t he inherit ance t ree unt il a m at ch is found.

3 .

I f no m at ch is found, t he receiver obj ect is sent t he forwardInvocation: m essage. I f t he obj ect im plem ent s t his m et hod, it has t he dynam ic abilit y t o resolve t he problem . This m et hod's default im plem ent at ion in NSObject sim ply announces ( wit h an error) t hat t he obj ect doesn't handle t he m essage.

4 .

1.2.3 Selectors

While user- friendly nam es refer t o m et hods in source code, t he runt im e uses a m uch m ore efficient m echanism . At com pile t im e, each m et hod is given a unique value of t ype SEL called a select or. When t he runt im e perform s t he m essage dispat ch described in t he previous sect ion, it resolves t he m essage t o a select or, which is t hen used t o execut e t he m et hod.

You can use select ors t o indicat e which m et hod should be called on an obj ect . The following exam ple shows how t o use t he @selector declarat ion t o get a select or and perform it s m et hod on an obj ect :

SEL playSelector = @selector(play); [iPod performSelector:playSelector];

A select or ident ifies a m et hod and is not associat ed wit h any part icular class. Assum ing t hat a Child

class is defined and im plem ent s a play m et hod, t he following would be valid:

[aChild performSelector:playSelector];

(29)

[iPodArray makeObjectsPerformSelector:playSelector];

You will also see select ors in t he Cocoa fram ework used in t he Target / Act ion paradigm . For m ore inform at ion about using select ors t o call m et hods on obj ect s, see t he NSInvocation class

docum ent at ion in Chapt er 14.

(30)

[ Team LiB ]

1.3 Classes

Obj ect s in Obj ect ive- C are defined in t erm s of a class. New classes of obj ect s are specializat ions of a m ore general class. Each new class is t he accum ulat ion of t he class definit ions t hat it inherit s from and can expand on t hat definit ion by adding new m et hods and inst ance variables or redefining exist ing m et hods t o perform new or expanded funct ionalit y. Like Java and Sm allt alk, but unlike C+ + ,

Obj ect ive- C is a single inherit ance language, m eaning t hat a class can inherit funct ionalit y only from a single class.

A class is not j ust a blueprint for building obj ect s; it is it self an obj ect in t he runt im e t hat knows how t o build new obj ect s. These new obj ect s are inst ances of t he class.

1.3.1 The Root Class

Every class hierarchy begins wit h a root class t hat has no superclass. While it is possible t o define your own root class in Obj ect ive- C, t he classes you define should inherit , direct ly or indirect ly, from t he

NSObject class provided by t he Foundat ion fram ework. The NSObject class defines t he behavior required for an obj ect t o be used by t he Cocoa fram ework and provides t he following funct ionalit y:

Defines t he low- level funct ionalit y needed t o handle obj ect init ializat ion, duplicat ion, and destruction.

Provides m echanism s t o aid Cocoa's m em ory m anagem ent m odel.

Defines funct ionalit y for an obj ect t o ident ify it s class m em bership and provide a reasonable descript ion of t he obj ect .

1.3.2 Defining a Class

I n Obj ect ive- C, classes are defined in t wo part s, usually separat ed int o t wo different files:

An int erface, which declares a class's m et hods and inst ance variables, and nam es it s superclass. The int erface is usually specified in a file wit h t he .h suffix t ypical of C header files.

An im plem ent at ion, which cont ains t he code t hat defines t he class's m et hods. By convent ion, files cont aining t he im plem ent at ion of a class have a .m suffix.

1.3.2.1 The interface

To declare a class and give all t he inform at ion ot her classes ( and ot her program s) need t o use it , an int erface file needs t o cont ain t he following inform at ion:

The class t hat is being inherit ed from

The inst ance variables, if any, t hat t he class adds

(31)

Exam ple 1- 1 shows sim ple header file, saved by convent ion as Song.h, cont aining t he int erface for t he

Song class.

Ex a m ple 1 - 1 . A sim ple h e a de r file for t h e Son g cla ss

#import <Cocoa/Cocoa.h> // 1

@interface Song : NSObject { // 2 id title; // 3 }

- (id)title; // 4 - (void)setTitle:(id)aTitle; // 5

@end; // 6

Each line is defined as follows:

I m port s t he definit ions for t he Cocoa fram eworks. This line is sim ilar t o t he #include direct ive in C, except t he com piler ensures t hat it doesn't include a header file m ore t han once.

1 .

Declares t he nam e of t he class, Song, and specifies NSObject as it s superclass. 2 .

Declares an inst ance variable nam ed title. The id t ype indicat es t hat t he variable is an obj ect . I f we want ed t he com piler t o enforce t ype checking for us, we could declare it s t ype as NSString *.

3 .

Declares an inst ance m et hod nam ed title t hat ret urns an obj ect . The - ( m inus sign) before t he m et hod nam e indicat es t hat t he m et hod is an inst ance m et hod.

4 .

Declares an inst ance m et hod nam ed setTitle t hat t akes an obj ect argum ent and doesn't ret urn anything.

5 .

The @end; st at em ent indicat es t o t he com piler t he end of t he Song class int erface. 6 .

1.3.2.2 Scoping instance variables

The obj ect - orient ed principle of encapsulat ion m eans t hat ot her program m ers shouldn't need t o know a class's inst ance variables. I nst ead, t hey need t o know only t he m essages t hat can be sent t o a class. The inclusion of inst ance variables in t he int erface file, while required by C, would seem t o break encapsulation.

To give a class t he abilit y t o enforce encapsulat ion even t hough t he variables are declared in t he header file, t he com piler lim it s t he scope of t he class's inst ance variables t o t he class t hat declares t hem and it s subclasses. This enforcem ent can be changed by using t he following set of com piler directives:

@private

These inst ances are accessible wit hin t he class from which t hey are declared. Subclasses will not be able t o access t hem .

@protected

These inst ances are available wit hin t he class t hat declares t hem and wit hin classes t hat inherit from t hem . This is a variable's default scope.

@public

(32)

it defeat s t he purpose of encapsulat ion.

For exam ple, t o ensure t hat subclasses of t he Song class could not direct ly access t he t it le inst ance variable, use t he @private direct ive as shown in Exam ple 1- 2.

Ex a m ple 1 - 2 . Con st r a in in g a va r ia ble 's scope

#import <Cocoa/Cocoa.h>

@interface Song : NSObject { @private

id title; }

- (id)title;

- (void)setTitle:(id)aTitle;

@end;

1.3.2.3 The implementation

To define how t he class works, an im plem ent at ion file needs t o cont ain im plem ent at ions of t he

m et hods defined in t he int erface file. Exam ple 1- 3 shows t he im plem ent at ion, cont ained in t he source file Song.m by convent ion, of t he Song class.

Ex a m ple 1 - 3 . I m ple m e n t a t ion of t h e Son g cla ss

#import Song.h // 1

@implementation Song // 2

- (id)title { // 3 return title;

}

- (void)setTitle:(id)aTitle { // 4 [title autorelease];

title = [aTitle retain]; }

@end // 5

Here is a det ailed explanat ion of each part of t his code:

I m port s t he header file t hat cont ains t he int erface for t he file. Every im plem ent at ion m ust

import it s own int erface. 1 .

Declares t hat what follows is t he implementation of t he Song class. 2 .

I m plem ent at ion of t he title m et hod. This m et hod sim ply ret urns t he title variable's value. The cont ent s of a m et hod are defined, like C funct ions, bet ween a pair of braces. Also, t he class's inst ance variables are in t he scope of t he m et hod and can be referred t o direct ly.

3 .

I m plem ent at ion of t he setTitle m et hod. This m et hod set s t he title variable t o t he aTitle

argum ent aft er perform ing som e st eps, using t he retain and autorelease m essages required for proper m em ory m anagem ent . For m ore inform at ion about m em ory m anagem ent , see Sect ion 1.5, lat er in t his chapt er.

4 .

(33)

I ndicat es t o t he com piler t he end of t he Song class im plem ent at ion. 5 .

Not ice t hat t he im plem ent at ion doesn't need t o repeat t he superclass nam e or t he inst ance variable declarations.

1.3.3 Special Variables

I n addit ion t o a class's inst ance variables, several ot her inst ance variables are defined wit hin t he scope of inst ance m et hods. These variables are:

isa

Defined by t he NSObject class, t he isa variable cont ains a point er t o t he class obj ect . This let s an obj ect int rospect it self. I t is also what let s t he runt im e det erm ine what kind of obj ect it is when it resolves m essages t o m et hods.

self

A variable set by t he runt im e t o point at t he obj ect t he act ion is perform ed on—t he receiver obj ect of t he m essage. This allows t he funct ionalit y wit hin a m et hod t o send m essages t o t he obj ect on which t he m et hod act s.

super

A variable set by t he runt im e t hat behaves sim ilarly t o self, except t hat t he resolut ion of m essage t o m et hod st art s wit h t he obj ect 's superclass. This allows you t o call t he funct ionalit y of superclasses.

_cmd

The select or used t o call t he current m et hod.

1.3.4 Class Methods

Since classes are obj ect s, you can define m et hods t hat will act when m essages are sent t o a class. Class m et hods are defined in t he sam e way as inst ance m et hods, except you use a plus sym bol (+) at t he beginning of t he m et hod declarat ion inst ead of a hyphen or m inus sign ( - ) . For exam ple, if t he

Song class keeps t rack of t he num ber of songs creat ed, a numberOfSongs class m et hod could be provided, as shown in Exam ple 1- 4.

Ex a m ple 1 - 4 . D e fin in g a cla ss m e t h od

#import <Cocoa/Cocoa.h>

@interface Song : NSObject { id title;

}

+ (int)numberOfSongs; - (id)title;

- (void)setTitle:(id)aTitle;

@end;

Sim ilarly, t his m et hod's im plem ent at ion is placed bet ween t he @implementation and @end direct ives in t he im plem ent at ion (.m) file. Since a class m et hod operat es on t he class obj ect , t he isa, self,

(34)

There is no class variable concept in Obj ect ive- C. However, you can achieve m uch t he sam e effect by declaring a C- st yle static variable in t he sam e file as t he class im plem ent at ion. This lim it s t he scope of t he variable t o t he .m file t hat cont ains it .

1.3.5 Overriding Superclass Methods

When a new class is defined, a m et hod can be im plem ent ed wit h t he sam e nam e as a m et hod in one of t he superclasses up t he inherit ance hierarchy. This new m et hod overrides t he original when

m essages wit h t he m et hod nam e are sent t o t he derived class's obj ect . When overriding m et hods, you can access t he superclass's m et hod funct ionalit y by sending a m essage t o t he special variable super.

For exam ple, if t he class of iPod inherit s from a m ore generic MP3Player class t hat also defines t he

play m et hod, t he subclass's play m et hod m ay require t hat t he superclass funct ionalit y is execut ed.

Exam ple 1- 5 shows how t his could be achieved by using t he super variable.

Ex a m ple 1 - 5 . Ove r r idin g a su pe r cla ss m e t h od

- (void)play {

[self setPlayIndicator:YES]; [super play];

}

When a superclass m et hod is overridden, t he m et hod doesn't need t o be declared again in t he int erface (.h) file. By convent ion, an overridden m et hod is list ed in t he int erface file only if you significant ly change t he way t he m et hod works.

Even t hough you can override m et hods of a superclass, you cannot override an inherit ed variable by declaring a new one wit h t he sam e nam e. The com piler will com plain if you t ry.

(35)

[ Team LiB ]

1.4 Creating Object Instances

One of t he principal funct ions of a class obj ect is t o serve as a fact ory for creat ing new inst ances. When new obj ect s are creat ed, m em ory is allocat ed and it s inst ance variables are init ialized. This is accom plished by using t he alloc m et hod, defined by t he NSObject class, as follows:

Song song = [song alloc];

The alloc class m et hod dynam ically allocat es m em ory, set s t he isa variable t o a point er t o t he class's class obj ect , set s all ot her variables t o 0, and t hen ret urns t he new obj ect inst ance. This t akes care of t he syst em level t asks t hat need t o be perform ed when an obj ect is creat ed, but doesn't allow t he obj ect t o properly init ialize it self. To give an opport unit y for obj ect - specific init ializat ion, t he

NSObject class provides t he init inst ance m et hod. To fully creat e an inst ance of t he Song class, use t he following code:

Song song = [[song alloc] init];

The init m et hod can be overridden in a subclass t o assign default s t o inst ance variables and t o t ake care of ot her t asks t hat need t o be perform ed before an obj ect is used.

You can call t he alloc and init m et hods by using separat e lines of code. However, since obj ect allocat ion and init ializat ion are int erlinked, calling bot h m et hods wit h one line of code is good pract ice.

When you override t he init m et hod, t he superclass's init m et hod ( or designat ed init ializer, as covered in t he next sect ion) should always be called t o ensure t hat t he superclass is init ialized properly. I nit ializat ion m et hods should also ret urn self, t he obj ect being init ialized. Exam ple 1- 6

shows an init m et hod for t he Song class.

Ex a m ple 1 - 6 . An in it ia liz a t ion m e t h od for t h e Son g cla ss

- (id)init { // 1 self = [super init]; // 2

// ... Song-specific initialization code

return self; // 3 }

The code shown in Exam ple 1- 6 perform s t he following t asks:

Declares t he init m et hod, which ret urns an obj ect of t ype id. The ret urned obj ect is t he newly init ialized obj ect .

1 .

Calls t he init m et hod of t he superclass (super) t o let it properly configure it s st at e. The self

variable is set t o t he ret urn value of t he init m et hod because it m ight ret urn a different inst ance t han t he one current ly being worked wit h.

2 .

Ret urns t he obj ect using t he self variable. 3 .

(36)

why you should m ake sure t hat self is set t o t he init m et hod's ret urn value.

The abilit y for an init ializat ion m et hod t o ret urn a subt ype allows for a

program m ing pat t ern known as class clust ers. This allows for a large am ount of funct ionalit y t o be exposed behind a sm all and easy t o underst and public class definit ion. For exam ple, t here are m any different st ring classes t hat are

represent ed by t he public NSString class.

1.4.1 Designated initializers

A class can provide m ult iple init ializat ion m et hods t o allow varying levels of cust om izat ion. When you have m ult iple init ializers, only t he designat ed init ializer should call t he superclass' init ializer m et hod. All ot her init ializers m ust call t he designat ed init ializer. This will ensure t hat your classes always behave properly.

For exam ple, if an initWithTitle: m et hod is defined for t he Song class, t he m ore general init

m et hod would first need t o be called t o allow proper init ializat ion of bot h t he Song class and it s parent classes before proceeding wit h specific init ializat ion. Exam ple 1- 7 shows an exam ple.

Ex a m ple 1 - 7 . Ca llin g a de sign a t e d in it ia liz e r

-(id)initWithTitle:(NSString *)aTitle { self = [self init];

[self setTitle:aTitle]; return self;

}

(37)

[ Team LiB ]

1.5 Memory Management

To properly m anage m em ory, Cocoa provides a reference count ing m echanism , support ed by t he

NSObject and NSAutoreleasePool classes. As it s nam e suggest s, reference count ing m aint ains a count of how m any references t here are t o an obj ect —indicat ing how m any ot her obj ect s are

int erest ed in keeping t he obj ect around. Reference count ing is not aut om at ic; t he com piler has no way t o det erm ine an obj ect 's lifet im e. Therefore, t he following NSObject reference count ing m et hods m ust be called t o indicat e t he level of int erest in an obj ect t o t he m em ory m anagem ent syst em :

retain

I ncrem ent s t he obj ect 's reference count by 1. When you want t o regist er int erest in an obj ect t hat you did not creat e or copy, indicat e int erest in it by calling t his m et hod.

release

Decrem ent s t he obj ect 's reference count by 1. This m essage is sent t o obj ect s creat ed wit h t he

alloc m et hod or sent a retain m essage when you are no longer int erest ed in using t hem . I f t his causes t he ret ain count t o reach 0, t he runt im e deallocat es t he obj ect .

autorelease

Adds t he obj ect t o t he current aut orelease pool. This allows you t o release your int erest in an obj ect wit hout im m ediat ely causing t he ret ain count t o reach 0. When t he aut orelease pool is it self released, it sends t he release m essage t o every obj ect it cont ains. This is m ost useful when you want t o pass t he obj ect t o anot her obj ect as a ret urn value and won't have t he opport unit y t o release t he obj ect lat er by yourself.

The following set of rules will help you perform accurat e reference count ing and avoid eit her leaking m em ory or prem at urely dest roying obj ect s:

Obj ect s creat ed by alloc or copy have a ret ain count of 1.

I f you want t o keep an obj ect received from anot her m echanism , send it a retain m essage.

When you are done wit h an obj ect creat ed by alloc or copy, or ret ained by t he retain

m essage, send it a release m essage.

When you add an obj ect t o a collect ion, such as an array or dict ionary ( described in Chapt er 2) , t he collect ion ret ains it . You are no longer responsible for t he obj ect , and you m ay safely release any int erest in it .

I f you need t o release int erest in an obj ect but need t o ensure t hat it is not im m ediat ely dest royed, send an autorelease m essage so t he obj ect is put in t he aut orelease pool for lat er release.

Once you have released int erest in an obj ect , you shouldn't send any m essages t o it . I f an obj ect is deallocat ed because it s ret ain count reached 0, sending a m essage t o t he obj ect will cause an error.

1.5.1 Retaining Objects in Accessor Methods

(38)

perform ed correct ly, send t he autorelease m et hod t o an old obj ect reference before replacing it wit h a new reference. Exam ple 1- 8 shows how t his rule is applied in t he Song class's setTitle: m et hod.

Ex a m ple 1 - 8 . M e m or y m a n a ge m e n t in a cce ssor m e t h ods

- (void)setTitle:(NSString *)aTitle { [title autorelease];

title = [aTitle retain]; }

Anot her way t o ensure proper m em ory m anagem ent and furt her increase encapsulat ion is t o m ake a copy of t he param et er, as shown in Exam ple 1- 9. This ensures t hat even if a m ut able subt ype of

NSString were given, any m odificat ions t o t hat param et er would not change t he cont ent s of t he

title variable.

Ex a m ple 1 - 9 . Copyin g a pa r a m e t e r t o e n for ce e n ca psu la t ion

- (void)setTitle:(NSString *)aTitle { [title autorelease];

title = [newTitle copy]; }

These pract ices ensure proper m em ory m anagem ent in alm ost all sit uat ions you are likely t o encount er. However, som e fringe cases require care in handling. For m ore det ails, see

http: / / www.stepwise.com / Articles/ Technical/ 2002- 06- 11.01.htm l.

(39)

[ Team LiB ]

1.6 Deallocating Objects

When an obj ect is ready t o be dest royed ( as det erm ined by t he reference count ing m echanism ) , t he syst em will give t he obj ect an opport unit y t o clean up aft er it self by calling t he dealloc m et hod defined by NSObject. I f t he obj ect has creat ed or ret ained any ot her obj ect s' reference by it s inst ance variables, it m ust im plem ent t his m et hod and perform t he appropriat e t asks t o m aint ain int egrit y of t he reference count ing syst em .

I n Exam ple 1- 8, t he Song class ret ains t he title inst ance variable in t he setTitle: m et hod. To properly im plem ent m em ory m anagem ent , you need t o balance t his ret ain wit h a release. Exam ple 1-10 shows t he release perform ed in t he Song class's dealloc m et hod.

Ex a m ple 1 - 1 0 . I m ple m e n t in g a de a lloc m e t h od

- (void)dealloc { [title release]; [super dealloc]; }

This provides proper balance in t he reference count ing m echanism .

You should never call t he dealloc m et hod yourself. Always let t he m em ory m anagem ent m et hods do it .

(40)

[ Team LiB ]

1.7 Categories

I nherit ance is not t he only way t o add funct ionalit y t o a class. Wit h an Obj ect ive- C language const ruct called a cat egory, you can add m et hods t o an exist ing class, t hereby ext ending it s funct ionalit y—and t he funct ionalit y of it s subclasses.

A cat egory int erface declarat ion looks like a class int erface declarat ion, wit h one except ion: t he cat egory nam e is list ed in parent heses aft er t he class nam e, and t he superclass is not m ent ioned. For exam ple, if you want ed t o add a rot13 m et hod t o t he NSString class t o get t he rot13 version of any st ring, t he cat egory int erface would be defined as shown in Exam ple 1- 11.

Ex a m ple 1 - 1 1 . D e fin in g a ca t e gor y in t e r fa ce

#import "NSString.h"

@interface NSString (Obfuscation)

- (NSString *)rot13;

@end

The cat egory's im plem ent at ion looks like t he im plem ent at ion of a class it self. Exam ple 1- 12 shows an int erface im plem ent at ion.

Ex a m ple 1 - 1 2 . I m ple m e n t a t ion of a ca t e gor y

#import "Obfuscation.h"

@implementation NSString (Obfuscation)

- (NSString *)rot13 {

NSString * rot13string;

// Perform logic to shift each character by 13

return rot13string; }

@end

Rem em ber t hat a cat egory can't declare new inst ance variables for a class; it can only add m et hods t o an exist ing class.

A cat egory is not a subst it ut e for a subclass. You should not redefine m et hods already in a class or a class's superclass—add only new m et hods t o t he class.

1.7.1 Protocols

(41)

prot ocol defines t he m et hods t hat a class is expect ed t o im plem ent in order t o funct ion appropriat ely while leaving t he im plem ent at ion of t hose m et hods t o t he class.

Like classes and cat egories, prot ocols are defined in int erface header (.h) files. To define a set of m et hods t hat apply t o obj ect s cont rolled by a m edia player, define t he prot ocol as shown in Exam ple 1-13.

Ex a m ple 1 - 1 3 . D e fin in g a pr ot ocol

@protocol Playable - (void)play; - (void)stop; @end

A class adopt s a prot ocol by list ing t he prot ocols in t he file's int erface declarat ion. Exam ple 1- 14 shows t he synt ax used in t he int erface declarat ion t o indicat e t hat t he Song class conform s t o t he Playable

protocol.

Ex a m ple 1 - 1 4 . Con for m in g t o a pr ot ocol in a cla ss in t e r fa ce

#import <Cocoa/Cocoa.h> #import "Playable.h"

@interface Song : NSObject <Playable> { id title;

}

- (id)title;

- (void)setTitle:(id)aTitle;

@end;

A class or cat egory t hat adopt s a prot ocol m ust im plem ent all m et hods defined by t hat prot ocol. The com piler issues a warning if t his requirem ent is not sat isfied. Addit ionally, you can check whet her or not obj ect s conform t o a part icular prot ocol. I f a m edia player want s t o m ake sure t hat t he Song class conform s t o t he Playable prot ocol, t he check in Exam ple 1- 15 could be used.

Ex a m ple 1 - 1 5 . Ch e ck in g t o se e if a n obj e ct con for m s t o a pr ot ocol

if([song conformsTo:@protocol(Playable)]) { [song play];

} else {

// Issue a warning or do something else reasonable here

}

(42)

[ Team LiB ]

1.8 Naming Conventions

Several nam ing convent ions have becom e widespread wit hin t he Obj ect ive- C com m unit y. To creat e code t hat your peers can m aint ain m ore easily, t ry t o use t he following convent ions:

Always capit alize class nam es.

Begin variable and m et hod nam es wit h lowercase let t ers. I f a variable or m et hod nam e consist s of m ult iple words, capit alize t he first let t er of t he second and any following words. This pract ice is known as cam elcase.

Begin accessor m et hods t hat set an inst ance variable value wit h t he word "set ," and m ake sure t he inst ance variable nam e follows in cam elcase.

Give accessor m et hods t hat ret urn t he value of an inst ance variable t he sam e nam e as t he variable. I t is also accept ableâ€

Gambar

Figure 3 -1 . MVC used to display tw o different view s of the sam e data
Figure 3 -2 . The File's Ow ner relationship betw een a nib and an object inan application
Figure 3 -5 . View  hierarchy of a sim ple Mail w indow
Figure 3 -6 . NSControl class hierarchy
+7

Referensi

Dokumen terkait

Dengan ini kami mengundang perusahaan saudara untuk mengikuti KLARIFIKASI PENAWARAN paket pekerjaan PENGADAAN KATINTING 9 PK yang insya allah akan diadakan pada

formulir isian kualifikasi yang di input di dalam Sistem Pengadaan Secara Elektronik (SPSE) pada alamat website LPSE, sesuai yang tertuang dalam Dokumen

The ironstone facies occurs as matrix to diamictites and as massive to laminated ironstones and comprises abundant Fe oxides (hematite, magnetite) and quartz, minor

Forward looking statements, by their nature, involve risk and uncertainty that could cause actual results and development to differ materially from those expressed or implied in

[r]

Melalui proses pertumbuhan organik, penggabungan usaha, serta akuisisi, KLBF telah tumbuh dan bertransformasi menjadi penyedia solusi kesehatan terintegrasi melalui

Formulir Penjualan Kembali Unit Penyertaan yang telah lengkap dan diterima secara baik ( in complete application ) serta telah memenuhi persyaratan dan ketentuan yang tercantum

The Java Platform, Standard Edition (SE), includes the Java Runtime Environment (JRE) and its encompassing Java Development Kit (JDK; see Chapter 10 ), the Java