0% found this document useful (0 votes)
130 views79 pages

The Objective C

The Objective C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views79 pages

The Objective C

The Objective C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 79

The Objective-C Programming

Language
Tools & Languages: Objective-C
2010-12-08
Apple Inc.
2010 Apple Inc.
All right reerve!.
"o part o# thi publication ma$ be repro!uce!%
tore! in a retrieval $tem% or tranmitte!% in
an$ #orm or b$ an$ mean% mechanical%
electronic% photocop$ing% recor!ing% or
other&ie% &ithout prior &ritten permiion o#
Apple Inc.% &ith the #ollo&ing e'ception( An$
peron i hereb$ authori)e! to tore
!ocumentation on a ingle computer #or
peronal ue onl$ an! to print copie o#
!ocumentation #or peronal ue provi!e! that
the !ocumentation contain Apple* cop$right
notice.
The Apple logo i a tra!emar+ o# Apple Inc.
"o licene% e'pre or implie!% are grante!
&ith repect to an$ o# the technolog$ !ecribe!
in thi !ocument. Apple retain all intellectual
propert$ right aociate! &ith the technolog$
!ecribe! in thi !ocument. Thi !ocument i
inten!e! to ait application !eveloper to
!evelop application onl$ #or Apple-labele!
computer.
Apple Inc.
1 In#inite Loop
Cupertino% CA ,-01.
.0/-,,0-1010
Apple% the Apple logo% Cocoa% i1oo+% i1oo+%
Intrument% 2ac% 2ac O3% an! Objective-C are
tra!emar+ o# Apple Inc.% regitere! in the
4nite! 3tate an! other countrie.
IO3 i a tra!emar+ or regitere! tra!emar+ o#
Cico in the 4.3. an! other countrie an! i ue!
un!er licene.
5ava i a regitere! tra!emar+ o# Oracle an!6or
it a##iliate.
Time i a regitere! tra!emar+ o# 7ei!elberger
8ruc+machinen A9% available #rom Linot$pe
Librar$ 9mb7.
Even though Apple has reviee! this !ocu"ent#
A$$LE %A&E' (O )A**A(T+ O* *E$*E'E(TAT,O(#
E,T-E* E.$*E'' O* ,%$L,E/# ),T- *E'$ECT TO
T-,' /OC0%E(T# ,T' 10AL,T+# ACC0*AC+#
%E*C-A(TA2,L,T+# O* 3,T(E'' 3O* A $A*T,C0LA*
$0*$O'E4 A' A *E'0LT# T-,' /OC0%E(T ,'
$*O5,/E/ 6A' ,'#7 A(/ +O0# T-E *EA/E*# A*E
A''0%,(8 T-E E(T,*E *,'& A' TO ,T' 10AL,T+
A(/ ACC0*AC+4
,( (O E5E(T ),LL A$$LE 2E L,A2LE 3O* /,*ECT#
,(/,*ECT# '$EC,AL# ,(C,/E(TAL# O*
CO('E10E(T,AL /A%A8E' *E'0LT,(8 3*O% A(+
/E3ECT O* ,(ACC0*AC+ ,( T-,' /OC0%E(T# even
i9 a!vise! o9 the possibilit: o9 such !a"ages4
T-E )A**A(T+ A(/ *E%E/,E' 'ET 3O*T- A2O5E
A*E E.CL0',5E A(/ ,( L,E0 O3 ALL OT-E*'# O*AL
O* )*,TTE(# E.$*E'' O* ,%$L,E/4 (o Apple
!ealer# agent# or e"plo:ee is authori;e! to "a<e
an: "o!i9ication# e=tension# or a!!ition to this
arrant:4
'o"e states !o not allo the e=clusion or li"itation
o9 i"plie! arranties or liabilit: 9or inci!ental or
conse>uential !a"ages# so the above li"itation or
e=clusion "a: not appl: to :ou4 This arrant: gives
:ou speci9ic legal rights# an! :ou "a: also have
other rights hich var: 9ro" state to state4
Content
,ntro!uction ,ntro!uction ?
:ho 3houl! ;ea! Thi 8ocument ,
Organi)ation o# Thi 8ocument ,
Convention 10
3ee Alo 11
The ;untime 3$tem 11
2emor$ 2anagement 11
Chapter 1 Objects# Classes# an! %essaging 1@
The ;untime 3$tem 1<
Object 1<
Object 1aic 1<
i! 1.
8$namic T$ping 1.
2emor$ 2anagement 1-
Object 2eaging 1-
2eage 3$nta' 1-
3en!ing 2eage to nil 1=
The ;eceiver* Intance >ariable 1/
Pol$morphim 1/
8$namic 1in!ing 1,
8$namic 2etho! ;eolution 1,
8ot 3$nta' 1,
Clae 2<
Inheritance 2<
Cla T$pe 20
Cla Object 2/
Cla "ame in 3ource Co!e <2
Teting Cla ?@ualit$ <<
Chapter 2 /e9ining a Class @A
3ource Aile <-
Cla Inter#ace <-
Importing the Inter#ace <=
;e#erring to Other Clae <=
The ;ole o# the Inter#ace </
Cla Implementation </
;e#erring to Intance >ariable <,
The 3cope o# Intance >ariable .0
@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
2eage to el# an! uper .<
An ?'ample( 4ing el# an! uper ..
4ing uper .-
;e!e#ining el# .0
Chapter @ Allocating an! ,nitiali;ing Objects D?
Allocating an! Initiali)ing Object .,
The ;eturne! Object .,
Implementing an Initiali)er -0
Contraint an! Convention -0
7an!ling Initiali)ation Aailure -2
Coor!inating Clae -<
The 8eignate! Initiali)er --
Combining Allocation an! Initiali)ation -=
Chapter D $rotocols A?
8eclaring Inter#ace #or Other to Implement -,
2etho! #or Other to Implement 00
8eclaring Inter#ace #or Anon$mou Object 01
"onhierarchical 3imilaritie 01
Aormal Protocol 02
8eclaring a Protocol 02
Optional Protocol 2etho! 02
In#ormal Protocol 0<
Protocol Object 0.
A!opting a Protocol 0.
Con#orming to a Protocol 0-
T$pe Chec+ing 0-
Protocol :ithin Protocol 00
;e#erring to Other Protocol 0=
Chapter A /eclare! $roperties E?
Overvie& 0,
Propert$ 8eclaration an! Implementation 0,
Propert$ 8eclaration =0
Propert$ 8eclaration Attribute =0
Propert$ Implementation 8irective =<
4ing Propertie =.
3upporte! T$pe =.
Propert$ ;e!eclaration =-
Cop$ =-
!ealloc =0
Core Aoun!ation ==
D
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
CO(TE(T'
?'ample( 8eclaring Propertie an! 3$nthei)ing Acceor ==
3ubclaing &ith Propertie =,
Per#ormance an! Threa!ing =,
;untime 8i##erence /0
Chapter E Categories an! E=tensions 81
A!!ing 2etho! to Clae /1
7o& Bou Can 4e Categorie /2
Categorie o# the ;oot Cla /<
?'tenion /<
Chapter F Associative *e9erences 8F
A!!ing 3torage Outi!e a Cla 8e#inition /=
Creating Aociation /=
;etrieving Aociate! Object //
1rea+ing Aociation //
Complete ?'ample //
Chapter 8 3ast Enu"eration ?1
The #orCin 3$nta' ,1
A!opting Aat ?numeration ,1
4ing Aat ?numeration ,2
Chapter ? Enabling 'tatic 2ehavior ?A
8e#ault 8$namic 1ehavior ,-
3tatic T$ping ,-
T$pe Chec+ing ,0
;eturn an! Parameter T$pe ,=
3tatic T$ping to an Inherite! Cla ,=
Chapter 10 'electors ??
2etho! an! 3elector ,,
3?L an! Delector ,,
2etho! an! 3elector 100
2etho! ;eturn an! Parameter T$pe 100
>ar$ing the 2eage at ;untime 100
The Target-Action 8eign Pattern 101
Avoi!ing 2eaging ?rror 101
A
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
CO(TE(T'
Chapter 11 E=ception -an!ling 10@
?nabling ?'ception-7an!ling 10<
?'ception 7an!ling 10<
Catching 8i##erent T$pe o# ?'ception 10.
Thro&ing ?'ception 10.
Chapter 12 Threa!ing 10F
/ocu"ent *evision -istor: 10?
8lossar: 11@
E
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
CO(TE(T'
Aigure an! Liting
Chapter 1 Objects# Classes# an! %essaging 1@
Aigure 1-1 3ome !ra&ing program clae 2.
Aigure 1-2 ;ectangle intance variable 2-
Aigure 1-< The inheritance hierarch$ #or "3Cell <0
Liting 1-1 Acceing propertie uing !ot $nta' 20
Liting 1-2 Acceing propertie uing brac+et $nta' 20
Liting 1-< Implementation o# the initiali)e metho! <2
Chapter 2 /e9ining a Class @A
Aigure 2-1 The cope o# intance variable E@package cope not ho&nF .1
Aigure 2-2 The hierarch$ o# 7igh% 2i!% an! Lo& ..
Chapter @ Allocating an! ,nitiali;ing Objects D?
Aigure <-1 Incorporating an inherite! initiali)ation metho! -.
Aigure <-2 Covering an inherite! initiali)ation metho! --
Aigure <-< Covering the !eignate! initiali)er -0
Aigure <-. The initiali)ation chain -=
Chapter A /eclare! $roperties E?
Liting --1 8eclaring a imple propert$ =0
Liting --2 4ing D$nthei)e =<
Liting --< 4ing D!$namic &ith "32anage!Object =.
Liting --. 8eclaring propertie #or a cla =/
Chapter F Associative *e9erences 8F
Liting =-1 ?tablihing an aociation bet&een an arra$ an! a tring /=
Chapter 11 E=ception -an!ling 10@
Liting 11-1 An e'ception han!ler 10.
Chapter 12 Threa!ing 10F
Liting 12-1 Loc+ing a metho! uing el# 10=
Liting 12-2 Loc+ing a metho! uing a cutom emaphore 10=
F
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
8
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
3,80*E' A(/ L,'T,(8'
The Objective-C language i a imple computer language !eigne! to enable ophiticate! object-oriente!
programming. Objective-C i !e#ine! a a mall but po&er#ul et o# e'tenion to the tan!ar! A"3I C
language. It a!!ition to C are motl$ bae! on 3malltal+% one o# the #irt object-oriente! programming
language. Objective-C i !eigne! to give C #ull object-oriente! programming capabilitie% an! to !o o in
a imple an! traight#or&ar! &a$.
2ot object-oriente! !evelopment environment conit o# everal part(
An object-oriente! programming language
A librar$ o# object
A uite o# !evelopment tool
A runtime environment
Thi !ocument i about the #irt component o# the !evelopment environmentGthe programming language.
It #ull$ !ecribe the verion o# the Objective-C language releae! in 2ac O3 H v10.0 an! iO3 ..0. Thi
!ocument
alo provi!e a #oun!ation #or learning about the econ! component% the Objective-C application
#rame&or+Gcollectivel$ +no&n a Cocoa. The runtime environment i !ecribe! in a eparate !ocument%
Objective-C Runtime Programming Guide.
:ho 3houl! ;ea! Thi 8ocument
The !ocument i inten!e! #or rea!er &ho might be interete! in(
Programming in Objective-C
Ain!ing out about the bai #or the Cocoa application #rame&or+
Thi !ocument both intro!uce the object-oriente! mo!el that Objective-C i bae! upon an! #ull$
!ocument
the language. It concentrate on the Objective-C e'tenion to C% not on the C language itel#.
1ecaue thi in*t a !ocument about C% it aume ome prior ac@uaintance &ith that language. Object-
oriente!
programming in Objective-C i% ho&ever% u##icientl$ !i##erent #rom proce!ural progra""ing in A"3I
C that
$ou &on*t be hampere! i# $ou*re not an e'perience! C programmer.
Organi)ation o# Thi 8ocument
The #ollo&ing chapter cover all the #eature Objective-C a!! to tan!ar! C.
:ho 3houl! ;ea! Thi 8ocument ?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
,(T*O/0CT,O(
Intro!uction
IObject% Clae% an! 2eagingJ Epage 1<F
I8e#ining a ClaJ Epage <-F
IAllocating an! Initiali)ing ObjectJ Epage .,F
IProtocolJ Epage -,F
I8eclare! PropertieJ Epage 0,F
ICategorie an! ?'tenionJ Epage /1F
IAociative ;e#erenceJ Epage /=F
IAat ?numerationJ Epage ,1F
I?nabling 3tatic 1ehaviorJ Epage ,-F
I3electorJ Epage ,,F
I?'ception 7an!lingJ Epage 10<F
IThrea!ingJ Epage 10=F
A gloar$ at the en! o# thi !ocument provi!e !e#inition o# term peci#ic to Objective-C an! object-
oriente!
programming.
Convention
Thi !ocument ma+e pecial ue o# computer voice an! italic #ont. Computer voice !enote &or! or
character that are to be ta+en literall$ Et$pe! a the$ appearF. Italic !enote &or! that repreent omething
ele or can be varie!. Aor e'ample% the $nta'(
@interfaceClassName(CategoryName)
mean that @interface an! the t&o parenthee are re@uire!% but that $ou can chooe the cla name an!
categor$ name.
:here e'ample co!e i ho&n% ellipi point in!icate the part% o#ten ubtantial part% that have been
omitte!(
- (void)encodeWithCoder:(NSCoder *)coder
{
[super encodeWithCoder:coder]
!!!
"
10 Convention
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
,(T*O/0CT,O(
Intro!uction
3ee Alo
I# $ou have never ue! object-oriente! programming to create application% $ou houl! rea! Object-
Oriented
Programming with Objective-C. Bou houl! alo coni!er rea!ing it i# $ou have ue! other object-
oriente!
!evelopment environment uch a CKK an! 5ava becaue the$ have man$ e'pectation an! convention
!i##erent #rom thoe o# Objective-C. Object-Oriented Programming with Objective-C i !eigne!
to help $ou
become #amiliar &ith object-oriente! !evelopment #rom the perpective o# an Objective-C !eveloper. It
pell out ome o# the implication o# object-oriente! !eign an! give $ou a #lavor o# &hat &riting an
object-oriente! program i reall$ li+e.
The ;untime 3$tem
Objective-C Runtime Programming Guide !ecribe apect o# the Objective-C runtime an! ho&
$ou can ue
it.
Objective-C Runtime Reference !ecribe the !ata tructure an! #unction o# the Objective-C
runtime upport
librar$. Bour program can ue thee inter#ace to interact &ith the Objective-C runtime $tem. Aor
e'ample%
$ou can a!! clae or metho!% or obtain a lit o# all cla !e#inition #or loa!e! clae.
2emor$ 2anagement
Objective-C upport t&o mechanim #or memor$ management( automatic garbage collection an!
re#erence
counting(
Garbage Collection Programming Guide !ecribe the garbage collection $tem ue! in 2ac O3
H. E"ot
available #or iO3G$ou cannot acce thi !ocument through the iO3 8ev Center.F
Memory Management Programming Guide !ecribe the re#erence counting $tem ue! in iO3
an!
2ac O3 H.
3ee Alo 11
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
,(T*O/0CT,O(
Intro!uction
12 3ee Alo
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
,(T*O/0CT,O(
Intro!uction
Thi chapter !ecribe the #un!amental o# object% clae% an! meaging a ue! an! implemente! b$ the
Objective-C language. It alo intro!uce the Objective-C runtime.
The ;untime 3$tem
The Objective-C language !e#er a man$ !eciion a it can #rom co"pile ti"e an! lin< ti"e to
runti"e.
:henever poible% it !$namicall$ per#orm operation uch a creating object an! !etermining &hat
metho! to invo+e. There#ore% the language re@uire not jut a compiler% but alo a runtime $tem to
e'ecute
the compile! co!e. The runtime $tem act a a +in! o# operating $tem #or the Objective-C languageL
it*
&hat ma+e the language &or+. T$picall$% ho&ever% $ou !on*t nee! to interact &ith the runtime !irectl$.
To
un!ertan! more about the #unctionalit$ it o##er% though% ee Objective-C Runtime Programming
Guide.
Object
A the name implie% object-oriente! program are built aroun! objects. An object aociate !ata &ith the
particular operation that can ue or a##ect that !ata. Objective-C provi!e a !ata t$pe to i!enti#$ an object
variable &ithout peci#$ing a particular cla o# the object.
Object 1aic
An object aociate !ata &ith the particular operation that can ue or a##ect that !ata. In Objective-C%
thee
operation are +no&n a the object* "etho!sL the !ata the$ a##ect are it instance variables Ein other
environment the$ ma$ be re#erre! to a ivars or member variablesF. In eence% an object bun!le a
!ata
tructure Eintance variableF an! a group o# proce!ure Emetho!F into a el#-containe! programming unit.
In Objective-C% an object* intance variable are internal to the objectL generall$% $ou get acce to an
object*
tate onl$ through the object* metho! E$ou can peci#$ &hether ubclae or other object can acce
intance variable !irectl$ b$ uing cope !irective% ee IThe 3cope o# Intance >ariableJ Epage .0FF. Aor
other to #in! out omething about an object% there ha to be a metho! to uppl$ the in#ormation. Aor
e'ample% a rectangle &oul! have metho! that reveal it i)e an! poition.
2oreover% an object ee onl$ the metho! that &ere !eigne! #or itL it can*t mita+enl$ per#orm metho!
inten!e! #or other t$pe o# object. 5ut a a C #unction protect it local variable% hi!ing them #rom the
ret
o# the program% an object hi!e both it intance variable an! it metho! implementation.
The ;untime 3$tem 1@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
i!
In Objective-C% object i!enti#ier are o# a !itinct !ata t$pe( id. Thi t$pe i the general t$pe #or an$ +in! o#
object regar!le o# cla an! can be ue! #or intance o# a cla an! #or cla object themelve.
id an#$%ect
Aor the object-oriente! contruct o# Objective-C% uch a metho! return value% id replace int a the
!e#ault !ata t$pe. EAor trictl$ C contruct% uch a #unction return value% int remain the !e#ault t$pe.F
The +e$&or! ni& i !e#ine! a a null object% an id &ith a value o# '. id% ni&% an! the other baic t$pe o#
Objective-C are !e#ine! in the hea!er #ile o$%c(o$%c!h.
id i !e#ine! a pointer to an object !ata tructure(
t)pedef struct o$%c*o$%ect {
C&ass isa
" *id
?ver$ object thu ha an isa variable that tell it o# &hat cla it i an intance. 3ince the C&ass t$pe i
itel#
!e#ine! a a pointer(
t)pedef struct o$%c*c&ass *C&ass
the isa variable i #re@uentl$ re#erre! to a the Iisa pointer.J
8$namic T$ping
The id t$pe i completel$ nonretrictive. 1$ itel#% it $iel! no in#ormation about an object% e'cept that it
i
an object. At ome point% a program t$picall$ nee! to #in! more peci#ic in#ormation about the object it
contain. 3ince the id t$pe !eignator can*t uppl$ thi peci#ic in#ormation to the compiler% each object
ha
to be able to uppl$ it at runtime.
The isa intance variable i!enti#ie the object* classG&hat +in! o# object it i. Object &ith the ame
behavior Emetho!F an! the ame +in! o# !ata Eintance variableF are member o# the ame cla.
Object are thu !:na"icall: t:pe! at runtime. :henever it nee! to% the runtime $tem can #in! the
e'act
cla that an object belong to% jut b$ a+ing the object. ETo learn more about the runtime% ee Objective-
C
Runtime Programming Guide.F 8$namic t$ping in Objective-C erve a the #oun!ation #or !$namic
bin!ing%
!icue! later.
The isa variable alo enable object to per#orm intropectionGto #in! out about themelve Eor other
objectF. The compiler recor! in#ormation about cla !e#inition in !ata tructure #or the runtime $tem
to ue. The #unction o# the runtime $tem ue isa to #in! thi in#ormation at runtime. 4ing the runtime
$tem% $ou can% #or e'ample% !etermine &hether an object implement a particular metho! or !icover the
name o# it upercla.
Object clae are !icue! in more !etail un!er IClaeJ Epage 2<F.
It* alo poible to give the compiler in#ormation about the cla o# an object b$ taticall$ t$ping it in
ource
co!e uing the cla name. Clae are particular +in! o# object% an! the cla name can erve a a t$pe
name. 3ee ICla T$peJ Epage 20F an! I?nabling 3tatic 1ehaviorJ Epage ,-F.
1D Object
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
2emor$ 2anagement
In an$ program% it i important to enure that object are !eallocate! &hen the$ are no longer
nee!e!Gother&ie $our application* memor$ #ootprint become larger than necear$. It i alo important
to enure that $ou !o not !eallocate object &hile the$*re till being ue!.
Objective-C o##er t&o mechanim #or memor$ management that allo& $ou to meet thee goal(
*e9erence counting% &here $ou are ultimatel$ reponible #or !etermining the li#etime o# object.
;e#erence counting i !ecribe! in Memory Management Programming Guide.
8arbage collection% &here $ou pa reponibilit$ #or !etermining the li#etime o# object to an
automatic
Icollector.J
9arbage collection i !ecribe! in Garbage Collection Programming Guide. E"ot available #or iO3
G$ou
cannot acce thi !ocument through the iO3 8ev Center.F
Object 2eaging
Thi ection e'plain the $nta' o# en!ing meage% inclu!ing ho& $ou can net meage e'preion. It
alo !icue the cope or Iviibilit$J o# an object* intance variable% an! the concept o# pol$morphim
an! !$namic bin!ing.
2eage 3$nta'
To get an object to !o omething% $ou en! it a "essage telling it to appl$ a metho!. In Objective-C%
"essage
e=pressions are encloe! in brac+et(
[receiver +essage]
The receiver i an object% an! the meage tell it &hat to !o. In ource co!e% the meage i impl$ the
name
o# a metho! an! an$ parameter that are pae! to it. :hen a meage i ent% the runtime $tem elect
the appropriate metho! #rom the receiver* repertoire an! invo+e it.
Aor e'ample% thi meage tell the +),ectang&e object to per#orm it disp&a) metho!% &hich caue
the
rectangle to !ipla$ itel#(
[+),ectang&e disp&a)]
The meage i #ollo&e! b$ a IJ a i normal #or an$ tatement in C.
1ecaue the metho! name in a meage erve to IelectJ a metho! implementation% metho! name in
meage are o#ten re#erre! to a selectors.
2etho! can alo ta+e parameter% ometime calle! arguments. A meage &ith a ingle parameter
a##i'e
a colon E:F to the name an! put the parameter right a#ter the colon(
[+),ectang&e setWidth:-'!']
Object 2eaging 1A
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
Aor metho! &ith multiple parameter% Objective-CM metho! name are interleave! &ith the parameter
uch that the metho!* name naturall$ !ecribe the parameter e'pecte! b$ the metho!. The imaginar$
meage belo& tell the +),ectang&e object to et it origin to the coor!inate E<0.0% -0.0F(
[+),ectang&e set#rigin.: /'!' ): 0'!'] (( 1his is a good e2a+p&e of
(( +u&tip&e para+eters
A elector name inclu!e all the part o# the name% inclu!ing the colon% o the elector in the prece!ing
e'ample i name! set#rigin.:):. It ha t&o colon% becaue it ta+e t&o parameter. The elector name
!oe not% ho&ever% inclu!e an$thing ele% uch a return t$pe or parameter t$pe.
,"portant: The ubpart o# an Objective-C elector name are not optional% nor can their or!er be varie!.
In
ome language% the term Iname! parameterJ an! I+e$&or! parameterJ carr$ the implication that the
parameter can var$ at runtime% can have !e#ault value% can be in a !i##erent or!er% an! can poibl$ have
a!!itional name! parameter. "one o# thee characteritic about parameter are true #or Objective-C.
Aor all intent an! purpoe% an Objective-C metho! !eclaration i impl$ a C #unction that prepen! t&o
a!!itional parameter Eee I2eagingJ in the Objective-C Runtime Programming GuideF. Thu%
the tructure
o# an Objective-C metho! !eclaration !i##er #rom the tructure o# a metho! that ue name! or +e$&or!
parameter in a language li+e P$thon% a the #ollo&ing P$thon e'ample illutrate(
def func(a3 $3 Neat4ode5SuperNeat3 1hing56efau&t1hing):
pass
In thi P$thon e'ample% 1hing an! Neat4ode might be omitte! or might have !i##erent value &hen
calle!.
In principle% a ,ectang&e cla coul! intea! implement a set#rigin:: metho! &ith no label #or the
econ! parameter% &hich &oul! be invo+e! a #ollo&(
[+),ectang&e set#rigin:/'!' :0'!'] (( 1his is a $ad e2a+p&e of +u&tip&e
para+eters
:hile $ntacticall$ legal% set#rigin:: !oe not interleave the metho! name &ith the parameter. Thu%
the econ! parameter i e##ectivel$ unlabele! an! it i !i##icult #or a rea!er o# thi co!e to !etermine the
+in!
or purpoe o# the metho!* parameter.
2etho! that ta+e a variable number o# parameter are alo poible% though the$*re ome&hat rare. ?'tra
parameter are eparate! b$ comma a#ter the en! o# the metho! name. E4nli+e colon% the comma are
not coni!ere! part o# the name.F In the #ollo&ing e'ample% the imaginar$ +ake7roup: metho! i pae!
one re@uire! parameter EgroupF an! three parameter that are optional(
[receiver +ake7roup:group3 +e+$er#ne3 +e+$er18o3 +e+$er1hree]
Li+e tan!ar! C #unction% metho! can return value. The #ollo&ing e'ample et the variable is9i&&ed
to
:;S i# +),ectang&e i !ra&n a a oli! rectangle% or N# i# it* !ra&n in outline #orm onl$.
<##= is9i&&ed
is9i&&ed 5 [+),ectang&e is9i&&ed]
"ote that a variable an! a metho! can have the ame name.
One meage e'preion can be nete! ini!e another. 7ere% the color o# one rectangle i et to the color o#
another(
[+),ectang&e set>ri+ar)Co&or:[other,ect pri+ar)Co&or]]
1E Object 2eaging
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
Objective-C alo provi!e a !ot E!F operator that o##er a compact an! convenient $nta' #or invo+ing an
object* acceor metho!. The !ot operator i t$picall$ ue! in conjunction &ith the !eclare! propertie
#eature Eee I8eclare! PropertieJ Epage 0,FF an! i !ecribe! in I8ot 3$nta'J Epage 1,F.
3en!ing 2eage to nil
In Objective-C% it i vali! to en! a meage to ni&Git impl$ ha no e##ect at runtime. There are everal
pattern in Cocoa that ta+e a!vantage o# thi #act. The value returne! #rom a meage to ni& ma$ alo be
vali!(
I# the metho! return an object% then a meage ent to ni& return ' Eni&F. Aor e'ample(
>erson *+other?n=a8 5 [[a>erson spouse] +other]
I# the spouse object here i ni&% then +other i ent to ni& an! the metho! return ni&.
I# the metho! return an$ pointer t$pe% an$ integer calar o# i)e le than or e@ual to si@eof(void*)%
a f&oat% a dou$&e% a &ong dou$&e% or a &ong &ong% then a meage ent to ni& return '.
I# the metho! return a struct% a !e#ine! b$ the Mac OS !"# $unction Call Guide to be
returne! in
regiter% then a meage ent to ni& return '!' #or ever$ #iel! in the struct. Other struct !ata t$pe
&ill not be #ille! &ith )ero.
I# the metho! return an$thing other than the a#orementione! value t$pe% the return value o# a meage
ent to ni& i un!e#ine!.
The #ollo&ing co!e #ragment illutrate a vali! ue o# en!ing a meage to ni&.
id an#$%ect4a)$eNi& 5 ni&
(( this is va&id
if ([an#$%ect4a)$eNi& +ethod1hat,eturnsA6ou$&e] 55 '!')
{
(( i+p&e+entation continues!!!
"
Object 2eaging 1F
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
(ote: The behavior o# en!ing meage to ni& change! lightl$ &ith 2ac O3 H v10.-.
In 2ac O3 H v10.. an! earlier% a meage to ni& alo i vali!% a long a the meage return an object%
an$
pointer t$pe% void% or an$ integer calar o# i)e le than or e@ual to si@eof(void*)L i# it !oe% a meage
ent to ni& return ni&. I# the meage ent to ni& return an$thing other than the a#orementione! value
t$pe E#or e'ample% i# it return an$ struct t$pe% an$ #loating-point t$pe% or an$ vector t$peF the return
value
i un!e#ine!. There#ore% in 2ac O3 H v10.. an! earlier% $ou houl! not rel$ on the return value o#
meage
ent to ni& unle the metho!* return t$pe i an object% an$ pointer t$pe% or an$ integer calar o# i)e le
than or e@ual to si@eof(void*).
The ;eceiver* Intance >ariable
A metho! ha automatic acce to the receiving object* intance variable. Bou !on*t nee! to pa them to
the metho! a parameter. Aor e'ample% the pri+ar)Co&or metho! illutrate! above ta+e no parameter%
$et it can #in! the primar$ color #or other,ect an! return it. ?ver$ metho! aume the receiver an! it
intance variable% &ithout having to !eclare them a parameter.
Thi convention impli#ie Objective-C ource co!e. It alo upport the &a$ object-oriente! programmer
thin+ about object an! meage. 2eage are ent to receiver much a letter are !elivere! to $our
home.
2eage parameter bring in#ormation #rom the outi!e to the receiverL the$ !on*t nee! to bring the
receiver
to itel#.
A metho! ha automatic acce onl$ to the receiver* intance variable. I# it re@uire in#ormation about a
variable tore! in another object% it mut en! a meage to the object a+ing it to reveal the content o#
the variable. The pri+ar)Co&or an! is9i&&ed metho! ho&n earlier are ue! #or jut thi purpoe.
3ee I8e#ining a ClaJ Epage <-F #or more in#ormation on re#erring to intance variable.
Pol$morphim
A the earlier e'ample illutrate% meage in Objective-C appear in the ame $ntactic poition a
#unction
call in tan!ar! C. 1ut% becaue metho! Ibelong toJ an object% meage !on*t behave in the ame &a$
that #unction call !o.
In particular% an object can be operate! on b$ onl$ thoe metho! that &ere !e#ine! #or it. It can*t con#ue
them &ith metho! !e#ine! #or other +in! o# object% even i# another object ha a metho! &ith the ame
name. There#ore% t&o object can repon! !i##erentl$ to the ame meage. Aor e'ample% each +in! o#
object
that receive a disp&a) meage coul! !ipla$ itel# in a uni@ue &a$. A Circ&e an! a ,ectang&e
&oul!
repon! !i##erentl$ to i!entical intruction to trac+ the curor.
Thi #eature% re#erre! to a pol:"orphis"% pla$ a igni#icant role in the !eign o# object-oriente!
program.
Together &ith !$namic bin!ing% it permit $ou to &rite co!e that might appl$ to an$ number o# !i##erent
+in! o# object% &ithout $ou having to chooe at the time $ou &rite the co!e &hat +in! o# object the$
might be. The$ might even be object that &ill be !evelope! later% b$ other programmer &or+ing on other
project. I# $ou &rite co!e that en! a disp&a) meage to an id variable% an$ object that ha a
disp&a)
metho! i a potential receiver.
18 Object 2eaging
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
8$namic 1in!ing
A crucial !i##erence bet&een #unction call an! meage i that a #unction an! it parameter are joine!
together in the compile! co!e% but a meage an! a receiving object aren*t unite! until the program i
running an! the meage i ent. There#ore% the e'act metho! invo+e! to repon! to a meage can be
!etermine! onl$ at runtime% not &hen the co!e i compile!.
:hen a meage i ent% a runtime meaging routine loo+ at the receiver an! at the metho! name! in the
meage. It locate the receiver* implementation o# a metho! matching the name% IcallJ the metho!% an!
pae it a pointer to the receiver* intance variable. EAor more on thi routine% ee I2eagingJ in
Objective-C
Runtime Programming Guide.F
Thi !:na"ic bin!ing o# metho! to meage &or+ han! in han! &ith pol$morphim to give object-
oriente!
programming much o# it #le'ibilit$ an! po&er. 1ecaue each object can have it o&n verion o# a metho!%
an Objective-C tatement can achieve a variet$ o# reult% not b$ var$ing the meage but b$ var$ing the
object that receive the meage. ;eceiver can be !eci!e! a the program runL the choice o# receiver can
be ma!e !epen!ent on #actor uch a uer action.
:hen e'ecuting co!e bae! upon the Application Nit EApp&itF% #or e'ample% uer !etermine &hich
object
receive meage #rom menu comman! uch a Cut% Cop$% an! Pate. The meage goe to &hatever
object
control the current election. An object that !ipla$ te't &oul! react to a cop) meage !i##erentl$ #rom
an object that !ipla$ canne! image. An object that repreent a et o# hape &oul! repon! !i##erentl$
to a cop) meage than a ,ectang&e &oul!. 1ecaue meage !o not elect metho! until runtime
E#rom
another perpective% becaue bin!ing o# metho! to meage !oe not occur until runtimeF% thee
!i##erence
in behavior are iolate! to the metho! themelve. The co!e that en! the meage !oen*t have to be
concerne! &ith themL it !oen*t even have to enumerate the poibilitie. An application* object can each
repon! in it o&n &a$ to cop) meage.
Objective-C ta+e !$namic bin!ing one tep #urther an! allo& even the meage that* ent Ethe metho!
electorF to be a variable !etermine! at runtime. Thi mechanim i !icue! in the ection I2eagingJ in
Objective-C Runtime Programming Guide.
8$namic 2etho! ;eolution
Bou can provi!e implementation o# cla an! intance metho! at runtime uing !$namic metho!
reolution.
3ee I8$namic 2etho! ;eolutionJ in Objective-C Runtime Programming Guide #or more !etail.
8ot 3$nta'
Objective-C provi!e a !ot E!F operator that o##er an alternative to @uare brac+et notation E[]F to invo+e
acceor metho!. 8ot $nta' ue the ame pattern that acceing C tructure element ue(
+)?nstance!va&ue 5 B'
printf(C+)?nstance va&ue: DdC3 +)?nstance!va&ue)
:hen ue! &ith object% ho&ever% !ot $nta' act a I$ntactic ugarJGit i tran#orme! b$ the compiler
into an invocation o# an acceor metho!. 8ot $nta' !oe not !irectl$ get or et an intance variable. The
co!e e'ample above i e'actl$ e@uivalent to the #ollo&ing(
[+)?nstance setEa&ue:B']
printf(C+)?nstance va&ue: DdC3 [+)?nstance va&ue])
Object 2eaging 1?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
A a corollar$% i# $ou &ant to acce an object* o&n intance variable uing acceor metho!% $ou mut
e'plicitl$ call out se&f% #or e'ample(
se&f!age 5 B'
or the e@uivalent(
[se&f setAge:B']
I# $ou !o not ue se&f!% $ou acce the intance variable !irectl$. In the #ollo&ing e'ample% the et
acceor
metho! #or age i not invo+e!(
age 5 B'
An a!vantage o# !ot $nta' i that it repreentation i more compact an! ma$ be more rea!able than the
correpon!ing @uare brac+et notation% particularl$ &hen $ou &ant to acce or mo!i#$ a propert$ that i a
propert$ o# another object Ethat i a propert$ o# another object% an! o onF. A #urther a!vantage i that the
compiler can ignal an error &hen it !etect an attempt to &rite to a rea!-onl$ !eclare! propert$. I# $ou
intea! ue @uare brac+et $nta' #or acceing variable% the compilerGat betGgenerate onl$ an
un!eclare!
metho! &arning that $ou invo+e! a none'itent etter metho!% an! the co!e #ail at runtime.
9eneral 4e
:hen $ou ue !ot $nta' to get a value% the $tem call the aociate! getter acceor metho!. 1$
!e#ault%
the getter metho! ha the ame name a the $mbol #ollo&ing the !ot. 4ing !ot $nta' to et a value call
the aociate! setter acceor metho!. 1$ !e#ault% the etter metho! i name! b$ capitali)ing the $mbol
#ollo&ing the !ot an! pre#i'ing it &ith Iet.J I# $ou !on*t &ant to ue !e#ault acceor name% $ou can
change
them b$ uing the !eclare! propertie #eature Eee I8eclare! PropertieJ Epage 0,FF.
Liting 1-1 illutrate everal ue cae.
Listing 1-1 Acceing propertie uing !ot $nta'
7raphic *graphic 5 [[7raphic a&&oc] init]
NSCo&or *co&or 5 graphic!co&or
C79&oat 2=oc 5 graphic!2=oc
<##= hidden 5 graphic!hidden
int te2tCharacter=ength 5 graphic!te2t!&ength
if (graphic!te2tFidden G5 :;S) {
graphic!te2t 5 @CFe&&oC (( @CFe&&oC is a constant NSString o$%ect!
"
graphic!$ounds 5 NS4ake,ect(B'!'3 B'!'3 -'!'3 B-'!')
The tatement in Liting 1-2 compile to e'actl$ the ame co!e a the tatement uing !ot $nta' ho&n
in Liting 1-1 Epage 20F% but intea! ue @uare brac+et $nta'.
Listing 1-2 Acceing propertie uing brac+et $nta'
7raphic *graphic 5 [[7raphic a&&oc] init]
NSCo&or *co&or 5 [graphic co&or]
C79&oat 2=oc 5 [graphic 2=oc]
<##= hidden 5 [graphic hidden]
int te2tCharacter=ength 5 [[graphic te2t] &ength]
20 Object 2eaging
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
if ([graphic is1e2tFidden] G5 :;S) {
[graphic set1e2t:@CFe&&oC]
"
[graphic set<ounds:NS4ake,ect(B'!'3 B'!'3 -'!'3 B-'!')]
Aor propertie o# the appropriate C language t$pe% the meaning o# compoun! aignment i &ell !e#ine!.
Aor e'ample% a$ $ou have an intance o# the NS4uta$&e6ata cla(
NS4uta$&e6ata *data 5 [NS4uta$&e6ata dataWith=ength:B'-H]
Bou coul! up!ate the length propert$ o# the intance uing !ot $nta' an! compoun! aignment(
data!&ength I5 B'-H
data!&ength *5 -
data!&ength (5 H
&hich i e@uivalent to the #ollo&ing @uare brac+et tatement(
[data set=ength:[data &ength] I B'-H]
[data set=ength:[data &ength] * -]
[data set=ength:[data &ength] ( H]
nil >alue
I# a ni& value i encountere! !uring propert$ traveral% the reult i the ame a en!ing the e@uivalent
meage to ni&. Aor e'ample% the #ollo&ing pair are all e@uivalent(
(( ;ach +e+$er of the path is an o$%ect!
2 5 person!address!street!na+e
2 5 [[[person address] street] na+e]
(( 1he path contains a C struct!
(( 1his 8i&& crash if 8indo8 is ni& or -contentEie8 returns ni&!
) 5 8indo8!contentEie8!$ounds!origin!)
) 5 [[8indo8 contentEie8] $ounds]!origin!)
(( An e2a+p&e of using a setter!
person!address!street!na+e 5 @C#2ford ,oadC
[[[person address] street] setNa+e: @C#2ford ,oadC]
Per#ormance an! Threa!ing
:hether $ou invo+e acceor metho! &ith !ot $nta' or @uare brac+et $nta'% the compiler generate
e@uivalent co!e. A a reult% the t&o co!ing techni@ue reult in e'actl$ the ame per#ormance. 1ecaue
uing !ot $nta' i impl$ a &a$ to invo+e acceor metho!% !oing o intro!uce no a!!itional threa!
!epen!encie.
8ot 3$nta' 4age
4e the Objective-C !ot $nta' to invo+e an acceor metho!% a an alternative to uing @uare brac+et
$nta'.
The #ollo&ing tatement invo+e the a>ropert) getter metho! an! aign the return value to
aEaria$&e(
Object 2eaging 21
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
aEaria$&e 5 an#$%ect!a>ropert)
The t$pe o# the a>ropert) propert$ an! the t$pe o# the aEaria$&e variable mut be compatible%
other&ie the compiler iue a &arning.
The #ollo&ing tatement invo+e the setNa+e: etter metho! on the an#$%ect object% paing @CNe8
Na+eC a the metho!* parameter(
an#$%ect!na+e 5 @CNe8 Na+eC
The compiler iue a &arning i# the setNa+e: metho! !oe not e'it% i# the propert$ na+e !oe not
e'it% or i# the setNa+e: metho! return an$thing but void.
The #ollo&ing tatement invo+e the $ounds metho! on the aEie8 object. It then aign to the
2#rigin
variable the value o# the origin!2 tructure element o# the NS,ect object returne! b$ the $ounds
metho!.
2#rigin 5 aEie8!$ounds!origin!2
The #ollo&ing tatement reult in the aignment o# the value o# BB to t&o propertie( the
integer>ropert) propert$ o# the an#$%ect object an! the f&oat>ropert) propert$ o# the
another#$%ect object.
NS?nteger i 5 B'
an#$%ect!integer>ropert) 5 another#$%ect!f&oat>ropert) 5 IIi
That i% the rightmot aignment i preevaluate! an! the reult i pae! to the set?nteger>ropert):
an! set9&oat>ropert): etter metho!. The !ata t$pe o# the preevaluate! reult i coerce! a re@uire!
at each point o# aignment.
Incorrect 4e o# 8ot 3$nta'
The co!e pattern that #ollo& are trongl$ !icourage! becaue the$ !o not con#orm to the inten!e! ue o#
!ot $nta'% namel$ #or invo+ing an acceor metho!.
The #ollo&ing tatement generate a compiler &arning E8arning: va&ue returned fro+
propert)
not used!F.
an#$%ect!retain
The #ollo&ing co!e generate a compiler &arning that set9oo?f:ouCan: !oe not appear to be a etter
metho! becaue it !oe not return (void).
(* 4ethod dec&aration! *(
- (<##=) set9oo?f:ouCan: (4)C&ass *)ne89oo
(* Code frag+ent! *(
an#$%ect!foo?f:ouCan 5 +)?nstance
The #ollo&ing tatement invo+e the &ock9ocus?fCan6ra8 metho! an! aign the return value to
f&ag. It !oe not generate a compiler &arning unle there i a mimatch bet&een the t$pe #or f&ag
an! the metho!* return t$pe. "onethele% thi pattern i trongl$ !icourage!.
f&ag 5 aEie8!&ock9ocus?fCan6ra8
22 Object 2eaging
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
The #ollo&ing co!e generate a compiler &arning becaue the readon&)>ropert) propert$ i !eclare!
&ith readon&) acce E8arning: assign+ent to readon&) propert) Jreadon&)>ropert)JF.
(* >ropert) dec&aration! *(
@propert)(readon&)) NS?nteger readon&)>ropert)
(* 4ethod dec&aration! *(
- (void) set,eadon&)>ropert): (NS?nteger)ne8Ea&ue
(* Code frag+ent! *(
se&f!readon&)>ropert) 5 0
?ven o% becaue the etter metho! i preent% thi co!e &or+ at runtime. Thi pattern i trongl$
!icourage! becaue impl$ a!!ing a etter #or a propert$ !oe not impl$ read8rite acce. 1e ure
to e'plicitl$ et propert$ acce correctl$ in a propert$* !eclaration tatement.
Clae
An object-oriente! program i t$picall$ built #rom a variet$ o# object. A program bae! on the Cocoa
#rame&or+ might ue NS4atri2 object% NSWindo8 object% NS6ictionar) object% NS9ont object%
NS1e2t object% an! man$ other. Program o#ten ue more than one object o# the ame +in! or claG
everal
NSArra) object or NSWindo8 object% #or e'ample.
In Objective-C% $ou !e#ine object b$ !e#ining their cla. The cla !e#inition i a protot$pe #or a +in! o#
objectL it !eclare the intance variable that become part o# ever$ member o# the cla% an! it !e#ine a et
o# metho! that all object in the cla can ue.
The compiler create jut one acceible object #or each cla% a class object that +no& ho& to buil! ne&
object belonging to the cla. EAor thi reaon it* tra!itionall$ calle! a factory object.F The cla object
i the
compile! verion o# the claL the object it buil! are instances o# the cla. The object that !o the main
&or+ o# $our program are intance create! b$ the cla object at runtime.
All intance o# a cla have the ame et o# metho!% an! the$ all have a et o# intance variable cut #rom
the ame mol!. ?ach object get it o&n intance variable% but the metho! are hare!.
1$ convention% cla name begin &ith an uppercae letter Euch a ,ectang&eFL the name o# intance
t$picall$ begin &ith a lo&ercae letter Euch a +),ectang&eF.
Inheritance
Cla !e#inition are a!!itiveL each ne& cla that $ou !e#ine i bae! on another cla #rom &hich it
inherit
metho! an! intance variable. The ne& cla impl$ a!! to or mo!i#ie &hat it inherit. It !oen*t nee!
to
!uplicate inherite! co!e.
,nheritance lin+ all clae together in a hierarchical tree &ith a ingle cla at it root. :hen &riting
co!e
that i bae! upon the Aoun!ation #rame&or+% that root cla i t$picall$ NS#$%ect. ?ver$ cla Ee'cept a
root claF ha a superclass one tep nearer the root% an! an$ cla Einclu!ing a root claF can be the
upercla
#or an$ number o# subclasses one tep #arther #rom the root. Aigure 1-1 illutrate the hierarch$ #or a #e&
o#
the clae ue! in a !ra&ing program.
Clae 2@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
3igure 1-1 3ome !ra&ing program clae
Image Text
NSObject
Graphic
Shape
Line Rectangle Circle
Square
Aigure 1-1 ho& that the SKuare cla i a ubcla o# the ,ectang&e cla% the ,ectang&e cla i a
ubcla
o# Shape% Shape i a ubcla o# 7raphic% an! 7raphic i a ubcla o# NS#$%ect. Inheritance i
cumulative.
3o a SKuare object ha the metho! an! intance variable !e#ine! #or ,ectang&e% Shape% 7raphic% an!
NS#$%ect% a &ell a thoe !e#ine! peci#icall$ #or SKuare. Thi i impl$ to a$ that an object o# t$pe
SKuare
in*t onl$ a @uare% it* alo a rectangle% a hape% a graphic% an! an object o# t$pe NS#$%ect.
?ver$ cla but NS#$%ect can thu be een a a peciali)ation or an a!aptation o# another cla. ?ach
ucceive
ubcla #urther mo!i#ie the cumulative total o# &hat* inherite!. The SKuare cla !e#ine onl$ the
minimum
nee!e! to turn a rectangle into a @uare.
:hen $ou !e#ine a cla% $ou lin+ it to the hierarch$ b$ !eclaring it uperclaL ever$ cla $ou create
mut
be the ubcla o# another cla Eunle $ou !e#ine a ne& root claF. Plent$ o# potential uperclae are
available. Cocoa inclu!e the NS#$%ect cla an! everal #rame&or+ containing !e#inition #or more
than
2-0 a!!itional clae. 3ome are clae that $ou can ue o## the hel# an! incorporate them into $our
program
a i. Other $ou might &ant to a!apt to $our o&n nee! b$ !e#ining a ubcla.
3ome #rame&or+ clae !e#ine almot ever$thing $ou nee!% but leave ome peci#ic to be implemente! in
a ubcla. Bou can thu create ver$ ophiticate! object b$ &riting onl$ a mall amount o# co!e an!
reuing
&or+ !one b$ the programmer o# the #rame&or+.
The "3Object Cla
NS#$%ect i a root cla% an! o !oen*t have a upercla. It !e#ine the baic #rame&or+ #or Objective-C
object an! object interaction. It impart to the clae an! intance o# clae that inherit #rom it the
abilit$
to behave a object an! cooperate &ith the runtime $tem.
A cla that !oen*t nee! to inherit an$ pecial behavior #rom another cla houl! neverthele be ma!e a
ubcla o# the NS#$%ect cla. Intance o# the cla mut at leat have the abilit$ to behave li+e
Objective-C
object at runtime. Inheriting thi abilit$ #rom the NS#$%ect cla i much impler an! much more reliable
than reinventing it in a ne& cla !e#inition.
2D Clae
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
(ote: Implementing a ne& root cla i a !elicate ta+ an! one &ith man$ hi!!en ha)ar!. The cla mut
!uplicate much o# &hat the NS#$%ect cla !oe% uch a allocate intance% connect them to their cla%
an! i!enti#$ them to the runtime $tem. Aor thi reaon% $ou houl! generall$ ue the NS#$%ect cla
provi!e! &ith Cocoa a the root cla. Aor more in#ormation% ee NSObject Class Reference an! the
NSObject
Protocol Reference.
Inheriting Intance >ariable
:hen a cla object create a ne& intance% the ne& object contain not onl$ the intance variable that
&ere !e#ine! #or it cla but alo the intance variable !e#ine! #or it upercla an! #or it upercla*
upercla% all the &a$ bac+ to the root cla. Thu% the isa intance variable !e#ine! in the NS#$%ect
cla
become part o# ever$ object. isa connect each object to it cla.
Aigure 1-2 ho& ome o# the intance variable that coul! be !e#ine! #or a particular implementation o# a
,ectang&e cla an! &here the$ ma$ come #rom. "ote that the variable that ma+e the object a rectangle
are a!!e! to the one that ma+e it a hape% an! the one that ma+e it a hape are a!!e! to the one that
ma+e it a graphic% an! o on.
3igure 1-2 ;ectangle intance variable
Class
NSPoint
NSColor
Pattern
. . .
float
float
BOOL
NSColor
. . .
declared in Shape
declared in Rectangle
declared in NSObject
declared in Graphic
isa;
origin;
*primaryColor;
linePattern;
width;
height;
filled;
*fillColor;
A cla !oen*t have to !eclare intance variable. It can impl$ !e#ine ne& metho! an! rel$ on the
intance
variable it inherit% i# it nee! an$ intance variable at all. Aor e'ample% SKuare might not !eclare an$
ne&
intance variable o# it o&n.
Inheriting 2etho!
An object ha acce not onl$ to the metho! !e#ine! #or it cla but alo to metho! !e#ine! #or it
upercla%
an! #or it upercla* upercla% all the &a$ bac+ to the root o# the hierarch$. Aor intance% a SKuare
object
can ue metho! !e#ine! in the ,ectang&e% Shape% 7raphic% an! NS#$%ect clae a &ell a metho!
!e#ine! in it o&n cla.
An$ ne& cla $ou !e#ine in $our program can there#ore ma+e ue o# the co!e &ritten #or all the clae
above it in the hierarch$. Thi t$pe o# inheritance i a major bene#it o# object-oriente! programming. :hen
$ou ue one o# the object-oriente! #rame&or+ provi!e! b$ Cocoa% $our program can ta+e a!vantage o#
the baic #unctionalit$ co!e! into the #rame&or+ clae. Bou have to a!! onl$ the co!e that cutomi)e the
tan!ar! #unctionalit$ to $our application.
Cla object alo inherit #rom the clae above them in the hierarch$. 1ut becaue the$ !on*t have
intance
variable Eonl$ intance !oF% the$ inherit onl$ metho!.
Clae 2A
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
Overri!ing One 2etho! &ith Another
There* one ue#ul e'ception to inheritance( :hen $ou !e#ine a ne& cla% $ou can implement a ne&
metho!
&ith the ame name a one !e#ine! in a cla #arther up the hierarch$. The ne& metho! overri!e the
originalL
intance o# the ne& cla per#orm it rather than the original% an! ubclae o# the ne& cla inherit it
rather
than the original.
Aor e'ample% 7raphic !e#ine a disp&a) metho! that ,ectang&e overri!e b$ !e#ining it o&n
verion o#
disp&a). The 7raphic metho! i available to all +in! o# object that inherit #rom the 7raphic claG
but
not to ,ectang&e object% &hich intea! per#orm the ,ectang&e verion o# disp&a).
Although overri!ing a metho! bloc+ the original verion #rom being inherite!% other metho! !e#ine! in
the ne& cla can +ip over the re!e#ine! metho! an! #in! the original Eee I2eage to el# an! uperJ
Epage
.<F to learn ho&F.
A re!e#ine! metho! can alo incorporate the ver$ metho! it overri!e. :hen it !oe% the ne& metho!
erve
onl$ to re#ine or mo!i#$ the metho! it overri!e% rather than replace it outright. :hen everal clae in the
hierarch$ !e#ine the ame metho!% but each ne& verion incorporate the verion it overri!e% the
implementation o# the metho! i e##ectivel$ prea! over all the clae.
Although a ubcla can overri!e inherite! metho!% it can*t overri!e inherite! intance variable. 1ecaue
an object ha memor$ allocate! #or ever$ intance variable it inherit% $ou can*t overri!e an inherite!
variable
b$ !eclaring a ne& one &ith the ame name. I# $ou tr$% the compiler &ill complain.
Abtract Clae
3ome clae are !eigne! onl$ or primaril$ o that other clae can inherit #rom them. Thee abstract
classes group metho! an! intance variable that can be ue! b$ a number o# ubclae into a common
!e#inition. The abtract cla i t$picall$ incomplete b$ itel#% but contain ue#ul co!e that re!uce the
implementation bur!en o# it ubclae. E1ecaue abtract clae mut have ubclae to be ue#ul%
the$*re
ometime alo calle! abstract superclasses.F
4nli+e ome other language% Objective-C !oe not have $nta' to mar+ clae a abtract% nor !oe it
prevent $ou #rom creating an intance o# an abtract cla.
The NS#$%ect cla i the canonical e'ample o# an abtract cla in Cocoa. Bou never ue intance o# the
NS#$%ect cla in an applicationGit &oul!n*t be goo! #or an$thingL it &oul! be a generic object &ith the
abilit$ to !o nothing in particular.
The NSEie8 cla% on the other han!% provi!e an e'ample o# an abtract cla% intance o# &hich $ou
might
occaionall$ ue !irectl$.
Abtract clae o#ten contain co!e that help !e#ine the tructure o# an application. :hen $ou create
ubclae o# thee clae% intance o# $our ne& clae #it e##ortlel$ into the application tructure an!
&or+ automaticall$ &ith other object.
Cla T$pe
A cla !e#inition i a peci#ication #or a +in! o# object. The cla% in e##ect% !e#ine a !ata t$pe. The t$pe i
bae! not jut on the !ata tructure the cla !e#ine Eintance variableF% but alo on the behavior inclu!e!
in the !e#inition Emetho!F.
2E Clae
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
A cla name can appear in ource co!e &herever a t$pe peci#ier i permitte! in CG#or e'ample% a an
argument to the si@eof operator(
int i 5 si@eof(,ectang&e)
3tatic T$ping
Bou can ue a cla name in place o# id to !eignate an object* t$pe(
,ectang&e *+),ectang&e
1ecaue thi &a$ o# !eclaring an object t$pe give the compiler in#ormation about the +in! o# object it i%
it* +no&n a static t:ping. 5ut a id i actuall$ a pointer% object are taticall$ t$pe! a pointer to a
cla.
Object are al&a$ t$pe! b$ a pointer. 3tatic t$ping ma+e the pointer e'plicitL id hi!e it.
3tatic t$ping permit the compiler to !o ome t$pe chec+ingG#or e'ample% to &arn i# an object coul!
receive
a meage that it appear not to be able to repon! toGan! to looen ome retriction that appl$ to object
genericall$ t$pe! id. In a!!ition% it can ma+e $our intention clearer to other &ho rea! $our ource co!e.
7o&ever% it !oen*t !e#eat !$namic bin!ing or alter the !$namic !etermination o# a receiver* cla at
runtime.
An object can be taticall$ t$pe! to it o&n cla or to an$ cla that it inherit #rom. Aor e'ample% becaue
inheritance ma+e a ,ectang&e object a +in! o# 7raphic object Ea ho&n in the e'ample hierarch$ in
Aigure 1-1 Epage 2.FF% a ,ectang&e intance can be taticall$ t$pe! to the 7raphic cla(
7raphic *+),ectang&e
3tatic t$ping to the upercla i poible here becaue a ,ectang&e object i a 7raphic object. In
a!!ition%
it* more than that becaue it alo ha the intance variable an! metho! capabilitie o# Shape an!
,ectang&e
object% but it* a 7raphic object nonethele. Aor purpoe o# t$pe chec+ing% given the !eclaration
!ecribe!
here% the compiler coni!er +),ectang&e to be o# t$pe 7raphic. At runtime% ho&ever% i# the
+),ectang&e
object i allocate! an! initiali)e! a an intance o# ,ectang&e% it i treate! a one.
3ee I?nabling 3tatic 1ehaviorJ Epage ,-F #or more on tatic t$ping an! it bene#it.
T$pe Intropection
Intance can reveal their t$pe at runtime. The is4e+$er#fC&ass: metho!% !e#ine! in the NS#$%ect
cla%
chec+ &hether the receiver i an intance o# a particular cla(
if ( [an#$%ect is4e+$er#fC&ass:so+eC&ass] )
!!!
The isLind#fC&ass: metho!% alo !e#ine! in the NS#$%ect cla% chec+ more generall$ &hether the
receiver inherit #rom or i a member o# a particular cla E&hether it ha the cla in it inheritance pathF(
if ( [an#$%ect isLind#fC&ass:so+eC&ass] )
!!!
The et o# clae #or &hich isLind#fC&ass: return :;S i the ame et to &hich the receiver can be
taticall$ t$pe!.
Intropection in*t limite! to t$pe in#ormation. Later ection o# thi chapter !icu metho! that return the
cla object% report &hether an object can repon! to a meage% an! reveal other in#ormation.
3ee NSObject Class Reference #or more on isLind#fC&ass:% is4e+$er#fC&ass:% an! relate!
metho!.
Clae 2F
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
Cla Object
A cla !e#inition contain variou +in! o# in#ormation% much o# it about intance o# the cla(
The name o# the cla an! it upercla
A template !ecribing a et o# intance variable
The !eclaration o# metho! name an! their return an! parameter t$pe
The metho! implementation
Thi in#ormation i compile! an! recor!e! in !ata tructure ma!e available to the runtime $tem. The
compiler create jut one object% a class object% to repreent the cla. The cla object ha acce to all the
in#ormation about the cla% &hich mean mainl$ in#ormation about &hat intance o# the cla are li+e. It*
able to pro!uce ne& intance accor!ing to the plan put #or&ar! in the cla !e#inition.
Although a cla object +eep the protot$pe o# a cla intance% it* not an intance itel#. It ha no intance
variable o# it o&n an! it can*t per#orm metho! inten!e! #or intance o# the cla. 7o&ever% a cla
!e#inition
can inclu!e metho! inten!e! peci#icall$ #or the cla objectGclass "etho!s a oppoe! to instance
"etho!s. A cla object inherit cla metho! #rom the clae above it in the hierarch$% jut a intance
inherit intance metho!.
In ource co!e% the cla object i repreente! b$ the cla name. In the #ollo&ing e'ample% the ,ectang&e
cla return the cla verion number uing a metho! inherite! #rom the NS#$%ect cla(
int versionNu+$er 5 [,ectang&e version]
7o&ever% the cla name tan! #or the cla object onl$ a the receiver in a meage e'preion.
?le&here%
$ou nee! to a+ an intance or the cla to return the cla id. 1oth repon! to a c&ass meage(
id aC&ass 5 [an#$%ect c&ass]
id rectC&ass 5 [,ectang&e c&ass]
A thee e'ample ho&% cla object can% li+e all other object% be t$pe! id. 1ut cla object can alo be
more peci#icall$ t$pe! to the C&ass !ata t$pe(
C&ass aC&ass 5 [an#$%ect c&ass]
C&ass rectC&ass 5 [,ectang&e c&ass]
All cla object are o# t$pe C&ass. 4ing thi t$pe name #or a cla i e@uivalent to uing the cla name to
taticall$ t$pe an intance.
Cla object are thu #ull-#le!ge! object that can be !$namicall$ t$pe!% receive meage% an! inherit
metho! #rom other clae. The$*re pecial onl$ in that the$*re create! b$ the compiler% lac+ !ata
tructure
Eintance variableF o# their o&n other than thoe built #rom the cla !e#inition% an! are the agent #or
pro!ucing intance at runtime.
28 Clae
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
(ote: The compiler alo buil! a metacla object #or each cla. It !ecribe the cla object jut a the
cla
object !ecribe intance o# the cla. 1ut &hile $ou can en! meage to intance an! to the cla
object%
the metacla object i ue! onl$ internall$ b$ the runtime $tem.
Creating Intance
A principal #unction o# a cla object i to create ne& intance. Thi co!e tell the ,ectang&e cla to
create
a ne& rectangle intance an! aign it to the +),ectang&e variable(
id +),ectang&e
+),ectang&e 5 [,ectang&e a&&oc]
The a&&oc metho! !$namicall$ allocate memor$ #or the ne& object* intance variable an! initiali)e
them
all to 'Gall% that i% e'cept the isa variable that connect the ne& intance to it cla. Aor an object to be
ue#ul% it generall$ nee! to be more completel$ initiali)e!. That* the #unction o# an init metho!.
Initiali)ation
t$picall$ #ollo& imme!iatel$ a#ter allocation(
+),ectang&e 5 [[,ectang&e a&&oc] init]
Thi line o# co!e% or one li+e it% &oul! be necear$ be#ore +),ectang&e coul! receive an$ o# the
meage
that &ere illutrate! in previou e'ample in thi chapter. The a&&oc metho! return a ne& intance an!
that intance per#orm an init metho! to et it initial tate. ?ver$ cla object ha at leat one metho!
Eli+e
a&&ocF that enable it to pro!uce ne& object% an! ever$ intance ha at leat one metho! Eli+e initF that
prepare it #or ue. Initiali)ation metho! o#ten ta+e parameter to allo& particular value to be pae! an!
have +e$&or! to label the parameter EinitWith>osition:si@e:% #or e'ample% i a metho! that might
initiali)e a ne& ,ectang&e intanceF% but ever$ initiali)ation metho! begin &ith IinitJ.
Cutomi)ation &ith Cla Object
It* not jut a &him o# the Objective-C language that clae are treate! a object. It* a choice that ha
inten!e!% an! ometime urpriing% bene#it #or !eign. It* poible% #or e'ample% to cutomi)e an object
&ith a cla% &here the cla belong to an open-en!e! et. In AppNit% #or e'ample% an NS4atri2 object
can
be cutomi)e! &ith a particular +in! o# NSCe&& object.
An NS4atri2 object can ta+e reponibilit$ #or creating the in!ivi!ual object that repreent it cell. It
can
!o thi &hen the matri' i #irt initiali)e! an! later &hen ne& cell are nee!e!. The viible matri' that an
NS4atri2 object !ra& on the creen can gro& an! hrin+ at runtime% perhap in repone to uer action.
:hen it gro&% the matri' nee! to be able to pro!uce ne& object to #ill the ne& lot that are a!!e!.
1ut &hat +in! o# object houl! the$ beO ?ach matri' !ipla$ jut one +in! o# NSCe&&% but there are man$
!i##erent +in!. The inheritance hierarch$ in Aigure 1-< ho& ome o# thoe provi!e! b$ AppNit. All
inherit
#rom the generic NSCe&& cla.
Clae 2?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
3igure 1-@ The inheritance hierarch$ #or "3Cell
NSObject
NSCell
NSActionCell
NSTextFieldCell NSButtonCell NSSliderCell NSFormCell
NSMenuCell
NSBrowserCell
:hen a matri' create NSCe&& object% houl! the$ be NS<uttonCe&& object to !ipla$ a ban+ o#
button
or &itche% NS1e2t9ie&dCe&& object to !ipla$ #iel! &here the uer can enter an! e!it te't% or ome
other +in! o# NSCe&&O The NS4atri2 object mut allo& #or an$ +in! o# cell% even t$pe that haven*t been
invente! $et.
One olution to thi problem &oul! be to !e#ine the NS4atri2 cla a abtract an! re@uire ever$one &ho
ue it to !eclare a ubcla an! implement the metho! that pro!uce ne& cell. 1ecaue the$ &oul! be
implementing the metho!% uer coul! ma+e certain that the object the$ create! &ere o# the right t$pe.
1ut thi olution &oul! re@uire uer o# the NS4atri2 cla to !o &or+ that ought to be !one in the
NS4atri2
cla itel#% an! it unnecearil$ proli#erate the number o# clae. 1ecaue an application might nee! more
than one +in! o# matri'% each &ith a !i##erent +in! o# cell% it coul! become cluttere! &ith NS4atri2
ubclae.
?ver$ time $ou invente! a ne& +in! o# NSCe&&% $ou*! alo have to !e#ine a ne& +in! o# NS4atri2.
2oreover%
programmer on !i##erent project &oul! be &riting virtuall$ i!entical co!e to !o the ame job% all to ma+e
up #or the #ailure o# NS4atri2 to !o it.
A better olution% an! the olution the NS4atri2 cla a!opt% i to allo& NS4atri2 intance to be
initiali)e!
&ith a +in! o# NSCe&&Gthat i% &ith a cla object. The NS4atri2 cla alo !e#ine a setCe&&C&ass:
metho! that pae the cla object #or the +in! o# NSCe&& object an NS4atri2 houl! ue to #ill empt$
lot(
[+)4atri2 setCe&&C&ass:[NS<uttonCe&& c&ass]]
The NS4atri2 object ue the cla object to pro!uce ne& cell &hen it* #irt initiali)e! an! &henever
it*
rei)e! to contain more cell. Thi +in! o# cutomi)ation &oul! be !i##icult i# clae &eren*t object that
coul! be pae! in meage an! aigne! to variable.
>ariable an! Cla Object
:hen $ou !e#ine a ne& cla% $ou can peci#$ intance variable. ?ver$ intance o# the cla can maintain
it
o&n cop$ o# the variable $ou !eclareGeach object control it o&n !ata. There i% ho&ever% no cla
variable
counterpart to an intance variable. Onl$ internal !ata tructure% initiali)e! #rom the cla !e#inition% are
provi!e! #or the cla. 2oreover% a cla object ha no acce to the intance variable o# an$ intanceL it
can*t initiali)e% rea!% or alter them.
Aor all the intance o# a cla to hare !ata% $ou mut !e#ine an e'ternal variable o# ome ort. The
implet
&a$ to !o thi i to !eclare a variable in the cla implementation #ile(
int 4C=S7&o$a&Earia$&e
@0 Clae
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
@i+p&e+entation 4)C&ass
(( i+p&e+entation continues
In a more ophiticate! implementation% $ou can !eclare a variable to be static% an! provi!e cla
metho!
to manage it. 8eclaring a variable static limit it cope to jut the claGan! to jut the part o# the cla
that* implemente! in the #ile. EThu unli+e intance variable% tatic variable cannot be inherite! b$% or
!irectl$ manipulate! b$% ubclae.F Thi pattern i commonl$ ue! to !e#ine hare! intance o# a cla
Euch a ingletonL ee ICreating a 3ingleton IntanceJ in Cocoa $undamentals GuideF.
static 4)C&ass *4C=SShared?nstance
@i+p&e+entation 4)C&ass
I (4)C&ass *)shared?nstance
{
(( check for e2istence of shared instance
(( create if necessar)
return 4C=SShared?nstance
"
(( i+p&e+entation continues
3tatic variable help give the cla object more #unctionalit$ than jut that o# a 9actor: pro!ucing
intanceL
it can approach being a complete an! veratile object in it o&n right. A cla object can be ue! to
coor!inate
the intance it create% !ipene intance #rom lit o# object alrea!$ create!% or manage other procee
eential to the application. In the cae &hen $ou nee! onl$ one object o# a particular cla% $ou can put all
the object* tate into tatic variable an! ue onl$ cla metho!. Thi ave the tep o# allocating an!
initiali)ing an intance.
(ote: It i alo poible to ue e'ternal variable that are not !eclare! static% but the limite! cope o#
tatic
variable better erve the purpoe o# encapulating !ata into eparate object.
Initiali)ing a Cla Object
I# $ou &ant to ue a cla object #or an$thing bei!e allocating intance% $ou ma$ nee! to initiali)e it jut
a $ou &oul! an intance. Although program !on*t allocate cla object% Objective-C !oe provi!e a &a$
#or program to initiali)e them.
I# a cla ma+e ue o# tatic or global variable% the initia&i@e metho! i a goo! place to et their
initial
value. Aor e'ample% i# a cla maintain an arra$ o# intance% the initia&i@e metho! coul! et up the
arra$ an! even allocate one or t&o !e#ault intance to have them rea!$.
The runtime $tem en! an initia&i@e meage to ever$ cla object be#ore the cla receive an$
other
meage an! a#ter it upercla ha receive! the initia&i@e meage. Thi e@uence give the cla a
chance to et up it runtime environment be#ore it* ue!. I# no initiali)ation i re@uire!% $ou !on*t nee! to
&rite an initia&i@e metho! to repon! to the meage.
1ecaue o# inheritance% an initia&i@e meage ent to a cla that !oen*t implement the initia&i@e
metho! i #or&ar!e! to the upercla% even though the upercla ha alrea!$ receive! the initia&i@e
meage. Aor e'ample% aume cla A implement the initia&i@e metho!% an! cla 1 inherit #rom
cla
A but !oe not implement the initia&i@e metho!. 5ut be#ore cla 1 i to receive it #irt meage% the
runtime $tem en! initia&i@e to it. 1ut% becaue cla 1 !oen*t implement initia&i@e% cla A*
initia&i@e i e'ecute! intea!. There#ore% cla A houl! enure that it initiali)ation logic i per#orme!
onl$ once% an! #or the appropriate cla.
Clae @1
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
To avoi! per#orming initiali)ation logic more than once% ue the template in Liting 1-< &hen
implementing
the initia&i@e metho!.
Listing 1-@ Implementation o# the initiali)e metho!
I (void)initia&i@e
{
if (se&f 55 [1hisC&ass c&ass]) {
(( >erfor+ initia&i@ation here!
!!!
"
"
(ote: ;emember that the runtime $tem en! initia&i@e to each cla in!ivi!uall$. There#ore% in a
cla*
implementation o# the initia&i@e metho!% $ou mut not en! the initia&i@e meage to it
upercla.
2etho! o# the ;oot Cla
All object% clae an! intance ali+e% nee! an inter#ace to the runtime $tem. 1oth cla object an!
intance houl! be able to intropect about their abilitie an! to report their place in the inheritance
hierarch$.
It* the province o# the NS#$%ect cla to provi!e thi inter#ace.
3o that NS#$%ect metho! !on*t have to be implemente! t&iceGonce to provi!e a runtime inter#ace #or
intance an! again to !uplicate that inter#ace #or cla objectGcla object are given pecial !ipenation
to per#orm intance metho! !e#ine! in the root cla. :hen a cla object receive a meage that it can*t
repon! to &ith a cla metho!% the runtime $tem !etermine &hether there* a root intance metho! that
can repon!. The onl$ intance metho! that a cla object can per#orm are thoe !e#ine! in the root cla%
an! onl$ i# there* no cla metho! that can !o the job.
Aor more on thi peculiar abilit$ o# cla object to per#orm root intance metho!% ee NSObject Class
Reference.
Cla "ame in 3ource Co!e
In ource co!e% cla name can be ue! in onl$ t&o ver$ !i##erent conte't. Thee conte't re#lect the !ual
role o# a cla a a !ata t$pe an! a an object(
The cla name can be ue! a a t$pe name #or a +in! o# object. Aor e'ample(
,ectang&e *an#$%ect
7ere an#$%ect i taticall$ t$pe! to be a pointer to a ,ectang&e object. The compiler e'pect it to
have the !ata tructure o# a ,ectang&e intance an! to have the intance metho! !e#ine! an! inherite!
b$ the ,ectang&e cla. 3tatic t$ping enable the compiler to !o better t$pe chec+ing an! ma+e ource
co!e more el#-!ocumenting. 3ee I?nabling 3tatic 1ehaviorJ Epage ,-F #or !etail.
Onl$ intance can be taticall$ t$pe!L cla object can*t be% becaue the$ aren*t member o# a cla%
but rather belong to the C&ass !ata t$pe.
A the receiver in a meage e'preion% the cla name re#er to the cla object. Thi uage &a
illutrate!
in everal o# the earlier e'ample. The cla name can tan! #or the cla object onl$ a a meage receiver.
In an$ other conte't% $ou mut a+ the cla object to reveal it id Eb$ en!ing it a c&ass meageF. Thi
e'ample pae the ,ectang&e cla a a parameter in an isLind#fC&ass: meage(
@2 Clae
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
if ( [an#$%ect isLind#fC&ass:[,ectang&e c&ass]] )
!!!
It &oul! have been illegal to impl$ ue the name I;ectangleJ a the parameter. The cla name can
onl$ be a receiver.
I# $ou !on*t +no& the cla name at compile time but have it a a tring at runtime% $ou can ue
NSC&ass9ro+String to return the cla object(
NSString *c&assNa+e
!!!
if ( [an#$%ect isLind#fC&ass:NSC&ass9ro+String(c&assNa+e)] )
!!!
Thi #unction return ni& i# the tring it* pae! i not a vali! cla name.
Cla name e'it in the ame namepace a global variable an! #unction name. A cla an! a global
variable
can*t have the ame name. Cla name are the onl$ name &ith global viibilit$ in Objective-C.
Teting Cla ?@ualit$
Bou can tet t&o cla object #or e@ualit$ uing a !irect pointer comparion. It i important% though% to get
the correct cla. There are everal #eature in the Cocoa #rame&or+ that !$namicall$ an! tranparentl$
ubcla e'iting clae to e'ten! their #unctionalit$ E#or e'ample% +e$-value oberving an! Core 8ata !o
thiGee %ey-&alue Observing Programming Guide an! Core 'ata Programming Guide
repectivel$F. In a
!$namicall$-create! ubcla% the c&ass metho! i t$picall$ overri!!en uch that the ubcla
ma@uera!e
a the cla it replace. :hen teting #or cla e@ualit$% $ou houl! there#ore compare the value returne!
b$ the c&ass metho! rather than thoe returne! b$ lo&er-level #unction. Put in term o# API% the
#ollo&ing
ine@ualitie pertain #or !$namic ubclae(
[o$%ect c&ass] G5 o$%ect*getC&ass(o$%ect) G5 *((C&ass*)o$%ect)
Bou houl! there#ore tet t&o clae #or e@ualit$ a #ollo&(
if ([o$%ectA c&ass] 55 [o$%ect< c&ass]) { ((!!!
Clae @@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
@D Clae
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 1
Object% Clae% an! 2eaging
2uch o# object-oriente! programming conit o# &riting the co!e #or ne& objectG!e#ining ne& clae.
In Objective-C% clae are !e#ine! in t&o part(
An inter9ace that !eclare the metho! an! intance variable o# the cla an! name it upercla
An i"ple"entation that actuall$ !e#ine the cla Econtain the co!e that implement it metho!F
?ach o# thee part i t$picall$ in it o&n #ile. 3ometime% ho&ever% a cla !e#inition pan everal #ile
through
the ue o# a #eature calle! a category. Categorie can compartmentali)e a cla !e#inition or e'ten! an
e'iting
one. Categorie are !ecribe! in ICategorie an! ?'tenionJ Epage /1F.
3ource Aile
Although the compiler !oen*t re@uire it% cla inter#ace an! implementation are uuall$ in t&o !i##erent
#ile.
The inter#ace #ile mut be ma!e available to an$one &ho ue the cla.
A ingle #ile can !eclare or implement more than one cla. "everthele% it* cutomar$ to have a eparate
inter#ace #ile #or each cla% i# not alo a eparate implementation #ile. Neeping cla inter#ace eparate
better
re#lect their tatu a in!epen!ent entitie.
Inter#ace an! implementation #ile t$picall$ are name! a#ter the cla. The name o# the implementation #ile
ha the !+ e'tenion% in!icating that it contain Objective-C ource co!e. The inter#ace #ile can be aigne!
an$ other e'tenion. 1ecaue it* inclu!e! in other ource #ile% the name o# the inter#ace #ile uuall$ ha
the
!h e'tenion t$pical o# hea!er #ile. Aor e'ample% the ,ectang&e cla &oul! be !eclare! in
,ectang&e!h
an! !e#ine! in ,ectang&e!+.
3eparating an object* inter#ace #rom it implementation #it &ell &ith the !eign o# object-oriente!
program.
An object i a el#-containe! entit$ that can be vie&e! #rom the outi!e almot a a blac+ bo'. Once $ou*ve
!etermine! ho& an object interact &ith other element in $our programGthat i% once $ou*ve !eclare! it
inter#aceG$ou can #reel$ alter it implementation &ithout a##ecting an$ other part o# the application.
Cla Inter#ace
The !eclaration o# a cla inter#ace begin &ith the compiler !irective @interface an! en! &ith the
!irective
@end. EAll Objective-C !irective to the compiler begin &ith IDJ.F
@interface C&assNa+e : ?tsSuperc&ass
{
instance varia$&e dec&arations
"
+ethod dec&arations
3ource Aile @A
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
@end
The #irt line o# the !eclaration preent the ne& cla name an! lin+ it to it upercla. The upercla
!e#ine the poition o# the ne& cla in the inheritance hierarch$% a !icue! un!er IInheritanceJ Epage
2<F. I# the colon an! upercla name are omitte!% the ne& cla i !eclare! a a root cla% a rival to the
NS#$%ect cla.
Aollo&ing the #irt part o# the cla !eclaration% brace encloe !eclaration o# instance variables% the
!ata
tructure that are part o# each intance o# the cla. 7ere* a partial lit o# intance variable that might be
!eclare! in the ,ectang&e cla(
f&oat 8idth
f&oat height
<##= fi&&ed
NSCo&or *fi&&Co&or
2etho! #or the cla are !eclare! ne't% a#ter the brace encloing intance variable an! be#ore the en! o#
the cla !eclaration. The name o# metho! that can be ue! b$ cla object% class "etho!s% are
prece!e!
b$ a plu ign(
I a&&oc
The metho! that intance o# a cla can ue% instance "etho!s% are mar+e! &ith a minu ign(
- (void)disp&a)
Although it* not a common practice% $ou can !e#ine a cla metho! an! an intance metho! &ith the ame
name. A metho! can alo have the ame name a an intance variable% &hich i more common% epeciall$ i#
the metho! return the value in the variable. Aor e'ample% Circ&e ha a radius metho! that coul! match
a radius intance variable.
2etho! return t$pe are !eclare! uing the tan!ar! C $nta' #or cating one t$pe to another(
- (f&oat)radius
Parameter t$pe are !eclare! in the ame &a$(
- (void)set,adius:(f&oat)a,adius
I# a return or parameter t$pe in*t e'plicitl$ !eclare!% it* aume! to be the !e#ault t$pe #or metho! an!
meageGan id. The a&&oc metho! illutrate! earlier return id.
:hen there* more than one parameter% the parameter are !eclare! &ithin the metho! name a#ter the
colon. Parameter brea+ the name apart in the !eclaration% jut a in a meage. Aor e'ample(
- (void)setWidth:(f&oat)8idth height:(f&oat)height
2etho! that ta+e a variable number o# parameter !eclare them uing a comma an! ellipi point% jut a
a #unction &oul!(
- +ake7roup:group3 !!!
@E Cla Inter#ace
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
Importing the Inter#ace
The inter#ace #ile mut be inclu!e! in an$ ource mo!ule that !epen! on the cla inter#aceGthat inclu!e
an$ mo!ule that create an intance o# the cla% en! a meage to invo+e a metho! !eclare! #or the cla%
or mention an intance variable !eclare! in the cla. The inter#ace i uuall$ inclu!e! &ith the Mi+port
!irective(
Mi+port C,ectang&e!hC
Thi !irective i i!entical to Minc&ude% e'cept that it ma+e ure that the ame #ile i never inclu!e! more
than once. It* there#ore pre#erre! an! i ue! in place o# Minc&ude in co!e e'ample throughout
Objective-CPbae! !ocumentation.
To re#lect the #act that a cla !e#inition buil! on the !e#inition o# inherite! clae% an inter#ace #ile
begin
b$ importing the inter#ace #or it upercla(
Mi+port C?tsSuperc&ass!hC
@interface C&assNa+e : ?tsSuperc&ass
{
instance varia$&e dec&arations
"
+ethod dec&arations
@end
Thi convention mean that ever$ inter#ace #ile inclu!e% in!irectl$% the inter#ace #ile #or all inherite!
clae.
:hen a ource mo!ule import a cla inter#ace% it get inter#ace #or the entire inheritance hierarch$ that
the cla i built upon.
"ote that i# there i a (recom(Ga precompile! hea!erGthat upport the upercla% $ou ma$ pre#er to
import the precomp intea!.
;e#erring to Other Clae
An inter#ace #ile !eclare a cla an!% b$ importing it upercla% implicitl$ contain !eclaration #or all
inherite! clae% #rom NS#$%ect on !o&n through it upercla. I# the inter#ace mention clae not in
thi hierarch$% it mut import them e'plicitl$ or !eclare them &ith the @c&ass !irective(
@c&ass ,ectang&e3 Circ&e
Thi !irective impl$ in#orm the compiler that I;ectangleJ an! ICircleJ are cla name. It !oen*t import
their inter#ace #ile.
An inter#ace #ile mention cla name &hen it taticall$ t$pe intance variable% return value% an!
parameter.
Aor e'ample% thi !eclaration
- (void)set>ri+ar)Co&or:(NSCo&or *)aCo&or
mention the NSCo&or cla.
1ecaue !eclaration li+e thi impl$ ue the cla name a a t$pe an! !on*t !epen! on an$ !etail o# the
cla inter#ace Eit metho! an! intance variableF% the @c&ass !irective give the compiler u##icient
#ore&arning o# &hat to e'pect. 7o&ever% &hen the inter#ace to a cla i actuall$ ue! Eintance create!%
Cla Inter#ace @F
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
meage entF% the cla inter#ace mut be importe!. T$picall$% an inter#ace #ile ue @c&ass to !eclare
clae% an! the correpon!ing implementation #ile import their inter#ace Eince it nee! to create
intance
o# thoe clae or en! them meageF.
The @c&ass !irective minimi)e the amount o# co!e een b$ the compiler an! lin+er% an! i there#ore the
implet &a$ to give a #or&ar! !eclaration o# a cla name. 1eing imple% it avoi! potential problem that
ma$ come &ith importing #ile that import till other #ile. Aor e'ample% i# one cla !eclare a taticall$
t$pe!
intance variable o# another cla% an! their t&o inter#ace #ile import each other% neither cla ma$ compile
correctl$.
The ;ole o# the Inter#ace
The purpoe o# the inter#ace #ile i to !eclare the ne& cla to other ource mo!ule Ean! to other
programmerF. It contain in#ormation the$ nee! to &or+ &ith the cla Eprogrammer might alo appreciate
a little !ocumentationF.
The inter#ace #ile tell uer ho& the cla i connecte! into the inheritance hierarch$ an! &hat other
claeGinherite! or impl$ re#erre! to ome&here in the claGare nee!e!.
The inter#ace #ile alo let the compiler +no& &hat intance variable an object contain% an! tell
programmer &hat variable ubclae inherit. Although intance variable are mot naturall$ vie&e!
a a matter o# the implementation o# a cla rather than it inter#ace% the$ mut neverthele be !eclare!
in the inter#ace #ile. Thi !eclaration i necear$ becaue the compiler mut be a&are o# the tructure
o# an object &here it* ue!% not jut &here it* !e#ine!. A a programmer% ho&ever% $ou can generall$
ignore the intance variable o# the clae $ou ue% e'cept &hen !e#ining a ubcla.
Ainall$% through it lit o# metho! !eclaration% the inter#ace #ile let other mo!ule +no& &hat meage
can be ent to the cla object an! intance o# the cla. ?ver$ metho! that can be ue! outi!e the
cla !e#inition i !eclare! in the inter#ace #ileL metho! that are internal to the cla implementation
can be omitte!.
Cla Implementation
The !e#inition o# a cla i tructure! ver$ much li+e it !eclaration. It begin &ith the @i+p&e+entation
!irective an! en! &ith the @end !irective(
@i+p&e+entation C&assNa+e : ?tsSuperc&ass
{
instance varia$&e dec&arations
"
+ethod definitions
@end
7o&ever% ever$ implementation #ile mut import it o&n inter#ace. Aor e'ample% ,ectang&e!+ import
,ectang&e!h. 1ecaue the implementation !oen*t nee! to repeat an$ o# the !eclaration it import% it can
a#el$ omit(
The name o# the upercla
The !eclaration o# intance variable
@8 Cla Implementation
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
Importing the inter#ace #ile impli#ie the implementation an! ma+e it mainl$ !evote! to metho!
!e#inition(
Mi+port CC&assNa+e!hC
@i+p&e+entation C&assNa+e
+ethod definitions
@end
2etho! #or a cla are !e#ine!% li+e C #unction% &ithin a pair o# brace. 1e#ore the brace% the$*re
!eclare!
in the ame manner a in the inter#ace #ile% but &ithout the emicolon. Aor e'ample(
I (id)a&&oc
{
!!!
"
- (<##=)is9i&&ed
{
!!!
"
- (void)set9i&&ed:(<##=)f&ag
{
!!!
"
2etho! that ta+e a variable number o# parameter han!le them jut a a #unction &oul!(
Mi+port Nstdarg!hO
!!!
- get7roup:group3 !!!
{
va*&ist ap
va*start(ap3 group)
!!!
"
;e#erring to Intance >ariable
1$ !e#ault% the !e#inition o# an intance metho! ha all the intance variable o# the object &ithin it cope.
It can re#er to them impl$ b$ name. Although the compiler create the e@uivalent o# C tructure to tore
intance variable% the e'act nature o# the tructure i hi!!en. Bou !on*t nee! either o# the tructure
operator
E! or -OF to re#er to an object* !ata. Aor e'ample% thi metho! !e#inition re#er to the receiver* fi&&ed
intance variable(
- (void)set9i&&ed:(<##=)f&ag
{
fi&&ed 5 f&ag
!!!
"
"either the receiving object nor it fi&&ed intance variable i !eclare! a a parameter to thi metho!% $et
the intance variable #all &ithin it cope. Thi impli#ication o# metho! $nta' i a igni#icant horthan!
in
the &riting o# Objective-C co!e.
Cla Implementation @?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
:hen the intance variable belong to an object that* not the receiver% the object* t$pe mut be ma!e
e'plicit to the compiler through tatic t$ping. In re#erring to the intance variable o# a taticall$ t$pe!
object%
the tructure pointer operator E-OF i ue!.
3uppoe% #or e'ample% that the Si$&ing cla !eclare a taticall$ t$pe! object% t8in% a an intance
variable(
@interface Si$&ing : NS#$%ect
{
Si$&ing *t8in
int gender
struct features *appearance
"
A long a the intance variable o# the taticall$ t$pe! object are &ithin the cope o# the cla Ea the$ are
here becaue t8in i t$pe! to the ame claF% a Si$&ing metho! can et them !irectl$(
- +ake?dentica&18in
{
if ( Gt8in ) {
t8in 5 [[Si$&ing a&&oc] init]
t8in-Ogender 5 gender
t8in-Oappearance 5 appearance
"
return t8in
"
The 3cope o# Intance >ariable
Although the$*re !eclare! in the cla inter#ace% intance variable are more a matter o# the &a$ a cla i
implemente! than o# the &a$ it* ue!. An object* inter#ace lie in it metho!% not in it internal !ata
tructure.
O#ten there* a one-to-one correpon!ence bet&een a metho! an! an intance variable% a in the #ollo&ing
e'ample(
- (<##=)is9i&&ed
{
return fi&&ed
"
1ut thi nee! not be the cae. 3ome metho! might return in#ormation not tore! in intance variable% an!
ome intance variable might tore in#ormation that an object i un&illing to reveal.
A a cla i revie! #rom time to time% the choice o# intance variable ma$ change% even though the
metho!
it !eclare remain the ame. A long a meage are the vehicle #or interacting &ith intance o# the cla%
thee change &on*t reall$ a##ect it inter#ace.
To en#orce the abilit$ o# an object to hi!e it !ata% the compiler limit the cope o# intance variableGthat
i% limit their viibilit$ &ithin the program. 1ut to provi!e #le'ibilit$% it alo let $ou e'plicitl$ et the
cope
at #our level. ?ach level i mar+e! b$ a compiler !irective(
/irective %eaning
@private The intance variable i acceible onl$ &ithin the cla that !eclare it.
D0 Cla Implementation
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
/irective %eaning
The intance variable i acceible &ithin the cla that !eclare it an! &ithin clae that
inherit it. All intance variable &ithout an e'plicit cope !irective have @protected cope.
@protected
@pu$&ic The intance variable i acceible ever$&here.
4ing the mo!ern runtime% an @package intance variable ha @pu$&ic cope ini!e the
e'ecutable image that implement the cla% but act li+e @private outi!e.
The @package cope #or Objective-C intance variable i analogou to private*e2tern
#or C variable an! #unction. An$ co!e outi!e the cla implementation* image that trie
to ue the intance variable get a lin+ error.
Thi cope i mot ue#ul #or intance variable in #rame&or+ clae% &here @private ma$
be too retrictive but @protected or @pu$&ic too permiive.
@package
Aigure 2-1 illutrate the level o# coping.
3igure 2-1 The cope o# intance variable E@package cope not ho&nF
Unrelated code
The class that
declares the
instance variable
A class that
inherits the
instance variable
@private
@protected
@public
A coping !irective applie to all the intance variable lite! a#ter it% up to the ne't !irective or the en! o#
the lit. In the #ollo&ing e'ample% the age an! eva&uation intance variable are privateL na+e% %o$%
an!
8age are protecte!L an! $oss i public.
@interface Worker : NS#$%ect
{
char *na+e
@private
int age
char *eva&uation
@protected
Cla Implementation D1
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
id %o$
f&oat 8age
@pu$&ic
id $oss
"
1$ !e#ault% all unmar+e! intance variable Eli+e na+e aboveF are @protected.
All intance variable that a cla !eclare% no matter ho& the$*re mar+e!% are &ithin the cope o# the cla
!e#inition. Aor e'ample% a cla that !eclare a %o$ intance variable% uch a the Worker cla ho&n
above%
can re#er to it in a metho! !e#inition(
- pro+ote1o:ne8>osition
{
id o&d 5 %o$
%o$ 5 ne8>osition
return o&d
"
Obvioul$% i# a cla coul!n*t acce it o&n intance variable% the intance variable &oul! be o# no ue
&hatoever.
"ormall$% a cla alo ha acce to the intance variable it inherit. The abilit$ to re#er to an intance
variable
i uuall$ inherite! along &ith the variable. It ma+e ene #or clae to have their entire !ata tructure
&ithin their cope% epeciall$ i# $ou thin+ o# a cla !e#inition a merel$ an elaboration o# the clae it
inherit
#rom. The pro+ote1o: metho! illutrate! earlier coul! jut a &ell have been !e#ine! in an$ cla that
inherit the %o$ intance variable #rom the Worker cla.
7o&ever% there are reaon &h$ $ou might &ant to retrict inheriting clae #rom !irectl$ acceing an
intance variable(
Once a ubcla accee an inherite! intance variable% the cla that !eclare the variable i tie! to that
part o# it implementation. In later verion% it can*t eliminate the variable or alter the role it pla$ &ithout
ina!vertentl$ brea+ing the ubcla.
2oreover% i# a ubcla accee an inherite! intance variable an! alter it value% it ma$ ina!vertentl$
intro!uce bug in the cla that !eclare the variable% epeciall$ i# the variable i involve! in cla-internal
!epen!encie.
To limit an intance variable* cope to jut the cla that !eclare it% $ou mut mar+ it @private. Intance
variable mar+e! @private are onl$ available to ubclae b$ calling public acceor metho!% i# the$
e'it.
At the other e'treme% mar+ing a variable @pu$&ic ma+e it generall$ available% even outi!e o# cla
!e#inition
that inherit or !eclare the variable. "ormall$% to get in#ormation tore! in an intance variable% other object
mut en! a meage re@ueting it. 7o&ever% a public intance variable can be accee! an$&here a i# it
&ere a #iel! in a C tructure. Aor e'ample(
Worker *ceo 5 [[Worker a&&oc] init]
ceo-O$oss 5 ni&
"ote that the object mut be taticall$ t$pe!.
2ar+ing intance variable @pu$&ic !e#eat the abilit$ o# an object to hi!e it !ata. It run counter to a
#un!amental principle o# object-oriente! programmingGthe encapulation o# !ata &ithin object &here
it* protecte! #rom vie& an! ina!vertent error. Public intance variable houl! there#ore be avoi!e! e'cept
in e'traor!inar$ cae.
D2 Cla Implementation
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
2eage to el# an! uper
Objective-C provi!e t&o term that can be ue! &ithin a metho! !e#inition to re#er to the object that
per#orm the metho!Gse&f an! super.
3uppoe% #or e'ample% that $ou !e#ine a reposition metho! that nee! to change the coor!inate o#
&hatever object it act on. It can invo+e the set#rigin:: metho! to ma+e the change. All it nee! to !o
i en! a set#rigin:: meage to the ame object that the reposition meage itel# &a ent to.
:hen
$ou*re &riting the repoition co!e% $ou can re#er to that object a either se&f or super. The reposition
metho! coul! rea! either(
- reposition
{
!!!
[se&f set#rigin:so+e. :so+e:]
!!!
"
or(
- reposition
{
!!!
[super set#rigin:so+e. :so+e:]
!!!
"
7ere% se&f an! super both re#er to the object receiving a reposition meage% &hatever object that
ma$
happen to be. The t&o term are @uite !i##erent% ho&ever. se&f i one o# the hi!!en parameter that the
meaging routine pae to ever$ metho!L it* a local variable that can be ue! #reel$ &ithin a metho!
implementation% jut a the name o# intance variable can be. super i a term that ubtitute #or se&f
onl$ a the receiver in a meage e'preion. A receiver% the t&o term !i##er principall$ in ho& the$
a##ect
the meaging proce(
se&f earche #or the metho! implementation in the uual manner% tarting in the !ispatch table o#
the receiving object* cla. In the e'ample above% it &oul! begin &ith the cla o# the object receiving
the repoition meage.
super tart the earch #or the metho! implementation in a ver$ !i##erent place. It begin in the
upercla
o# the cla that !e#ine the metho! &here super appear. In the e'ample above% it &oul! begin &ith
the upercla o# the cla &here repoition i !e#ine!.
:herever super receive a meage% the compiler ubtitute another meaging routine #or the
o$%c*+sgSend #unction. The ubtitute routine loo+ !irectl$ to the upercla o# the !e#ining claGthat
i% to the upercla o# the cla en!ing the meage to superGrather than to the cla o# the object
receiving
the meage.
2eage to el# an! uper D@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
An ?'ample( 4ing el# an! uper
The !i##erence bet&een se&f an! super become clear &hen uing a hierarch$ o# three clae. 3uppoe%
#or e'ample% that &e create an object belonging to a cla calle! =o8. The upercla o# =o8 i 4idL the
upercla o# 4id i Figh. All three clae !e#ine a metho! calle! negotiate% &hich each cla ue #or
it
o&n purpoe. In a!!ition% 4id !e#ine an ambitiou metho! calle! +ake=asting>eace% &hich itel#
emplo$
the negotiate metho!. The clae an! thoe metho! are illutrate! in Aigure 2-2.
3igure 2-2 The hierarch$ o# 7igh% 2i!% an! Lo&
Mid
High
Low
superclass
negotiate
superclass
negotiate
superclass
negotiate
makeLastingPeace
3uppoe that the implementation o# +ake=asting>eace Ein the 4id claF ue se&f to in!icate the
object
to en! the negotiate meage to(
- +ake=asting>eace
{
[se&f negotiate]
!!!
"
:hen a meage i ent to a =o8 object to per#orm the +ake=asting>eace metho!%
+ake=asting>eace
en! a negotiate meage to the ame =o8 object. The meaging routine #in! the verion o#
negotiate
!e#ine! in =o8% the cla o# se&f.
DD 2eage to el# an! uper
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
7o&ever% i# the implementation o# +ake=asting>eace intea! ue super a the receiver%
- +ake=asting>eace
{
[super negotiate]
!!!
"
the meaging routine #in! the verion o# negotiate !e#ine! in Figh. It ignore the cla E=o8F o# the
object that receive! the +ake=asting>eace meage an! +ip to the upercla o# 4id% becaue 4id i
&here +ake=asting>eace i !e#ine!. "either implementation #in! the 4id verion o# negotiate.
A thi e'ample illutrate% super provi!e a &a$ to b$pa a metho! that overri!e another metho!.
7ere%
the ue o# super enable! +ake=asting>eace to b$pa the 4id verion o# negotiate that re!e#ine!
the
Figh verion o# that metho!.
"ot being able to reach the 4id verion o# negotiate% a jut !ecribe!% ma$ eem li+e a #la&% but un!er
the circumtance it* intentional(
The author o# the =o8 cla intentionall$ overro!e the 4id verion o# negotiate o that intance o#
=o8 Ean! it ubclaeF &oul! invo+e the re!e#ine! verion o# the metho! intea!. The !eigner o# =o8
!i!n*t &ant =o8 object to per#orm the inherite! metho!.
The author o# the 4id metho! +ake=asting>eace% in en!ing the negotiate meage to super Ea
ho&n in the econ! implementationF% intentionall$ +ippe! over the 4id verion o# negotiate Ean!
over an$ verion that might be !e#ine! in clae li+e =o8 that inherit #rom 4idF to per#orm the verion
!e#ine! in the Figh cla. The !eigner o# the econ! implementation o# +ake=asting>eace &ante!
to ue the Figh verion o# negotiate an! no other.
The 4id verion o# negotiate coul! till be ue!% but it &oul! ta+e a !irect meage to a 4id intance
to
!o o.
4ing uper
2eage to super allo& metho! implementation to be !itribute! over more than one cla. Bou can
overri!e an e'iting metho! to mo!i#$ or a!! to it an! till incorporate the original metho! in the
mo!i#ication(
- negotiate
{
!!!
return [super negotiate]
"
Aor ome ta+% each cla in the inheritance hierarch$ can implement a metho! that !oe part o# the job
an! pae the meage on to super #or the ret. The init metho!% &hich initiali)e a ne&l$ allocate!
intance% i !eigne! to &or+ li+e thi. ?ach init metho! ha reponibilit$ #or initiali)ing the intance
variable !e#ine! in it cla. 1ut be#ore !oing o% it en! an init meage to super to have the clae
it
inherit #rom initiali)e their intance variable. ?ach verion o# init #ollo& thi proce!ure% o clae
initiali)e
their intance variable in the or!er o# inheritance(
- (id)init
{
se&f 5 [super init]
2eage to el# an! uper DA
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
if (se&f) {
!!!
"
"
Initiali)er metho! have ome a!!itional contraintL the$ are !ecribe! in more !etail in IAllocating an!
Initiali)ing ObjectJ Epage .,F.
It* alo poible to concentrate core #unctionalit$ in one metho! !e#ine! in a upercla an! have
ubclae
incorporate the metho! through meage to super. Aor e'ample% ever$ cla metho! that create an
intance
mut allocate torage #or the ne& object an! initiali)e it isa variable to the cla tructure. Allocation i
t$picall$ le#t to the a&&oc an! a&&ocWithPone: metho! !e#ine! in the NS#$%ect cla. I# another
cla
overri!e thee metho! Ea rare caeF% it can till get the baic #unctionalit$ b$ en!ing a meage to super.
;e!e#ining el#
super i impl$ a #lag to the compiler telling it &here to begin earching #or the metho! to per#ormL it*
ue!
onl$ a the receiver o# a meage. 1ut se&f i a variable name that can be ue! in an$ number o# &a$%
even
aigne! a ne& value.
There* a ten!enc$ to !o jut that in !e#inition o# cla metho!. Cla metho! are o#ten concerne! not
&ith the cla object% but &ith intance o# the cla. Aor e'ample% man$ cla metho! combine allocation
an! initiali)ation o# an intance% o#ten etting up intance variable value at the ame time. In uch a
metho!%
it might be tempting to en! meage to the ne&l$ allocate! intance an! to call the intance se&f% jut
a in an intance metho!. 1ut that &oul! be an error. se&f an! super both re#er to the receiving objectG
the
object that get a meage telling it to per#orm the metho!. Ini!e an intance metho!% se&f re#er to the
intanceL but ini!e a cla metho!% se&f re#er to the cla object. Thi i an e'ample o# &hat not to !o(
I (,ectang&e *)rectang&e#fCo&or:(NSCo&or *) co&or
{
se&f 5 [[,ectang&e a&&oc] init] (( <A6
[se&f setCo&or:co&or]
return [se&f autore&ease]
"
To avoi! con#uion% it* uuall$ better to ue a variable other than se&f to re#er to an intance ini!e a
cla
metho!(
I (id)rectang&e#fCo&or:(NSCo&or *)co&or
{
id ne8?nstance 5 [[,ectang&e a&&oc] init] (( 7##6
[ne8?nstance setCo&or:co&or]
return [ne8?nstance autore&ease]
"
In #act% rather than en!ing the a&&oc meage to the cla in a cla metho!% it* o#ten better to en!
a&&oc
to se&f. Thi &a$% i# the cla i ubclae!% an! the rectang&e#fCo&or: meage i receive! b$ a
ubcla%
the intance returne! i the ame t$pe a the ubcla E#or e'ample% the arra) metho! o# NSArra) i
inherite!
b$ NS4uta$&eArra)F.
I (id)rectang&e#fCo&or:(NSCo&or *)co&or
{
id ne8?nstance 5 [[se&f a&&oc] init] (( ;.C;==;N1
[ne8?nstance setCo&or:co&or]
return [ne8?nstance autore&ease]
DE 2eage to el# an! uper
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
"
3ee IAllocating an! Initiali)ing ObjectJ Epage .,F #or more in#ormation about object allocation.
2eage to el# an! uper DF
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
D8 2eage to el# an! uper
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 2
8e#ining a Cla
Allocating an! Initiali)ing Object
It ta+e t&o tep to create an object uing Objective-C. Bou mut(
8$namicall$ allocate memor$ #or the ne& object
Initiali)e the ne&l$ allocate! memor$ to appropriate value
An object in*t #ull$ #unctional until both tep have been complete!. ?ach tep i accomplihe! b$ a
eparate
metho! but t$picall$ in a ingle line o# co!e(
id an#$%ect 5 [[,ectang&e a&&oc] init]
3eparating allocation #rom initiali)ation give $ou control over each tep o that each can be mo!i#ie!
in!epen!entl$ o# the other. The #ollo&ing ection loo+ #irt at allocation an! then at initiali)ation an!
!icu
ho& the$ are controlle! an! mo!i#ie!.
In Objective-C% memor$ #or ne& object i allocate! uing cla metho! !e#ine! in the NS#$%ect cla.
NS#$%ect !e#ine t&o principal metho! #or thi purpoe% a&&oc an! a&&ocWithPone:.
Thee metho! allocate enough memor$ to hol! all the intance variable #or an object belonging to the
receiving cla. The$ !on*t nee! to be overri!!en an! mo!i#ie! in ubclae.
The a&&oc an! a&&ocWithPone: metho! initiali)e a ne&l$ allocate! object* isa intance variable o
that
it point to the object* cla Ethe cla objectF. All other intance variable are et to '. 4uall$% an object
nee! to be more peci#icall$ initiali)e! be#ore it can be a#el$ ue!.
Thi initiali)ation i the reponibilit$ o# cla-peci#ic intance metho! that% b$ convention% begin &ith
the
abbreviation IinitJ. I# the metho! ta+e no parameter% the metho! name i jut thoe #our letter% init. I#
it ta+e parameter% label #or the parameter #ollo& the IinitJ pre#i'. Aor e'ample% an NSEie8 object can
be
initiali)e! &ith an initWith9ra+e: metho!.
?ver$ cla that !eclare intance variable mut provi!e an init!!! metho! to initiali)e them. The
NS#$%ect
cla !eclare the isa variable an! !e#ine an init metho!. 7o&ever% becaue isa i initiali)e! &hen
memor$ #or an object i allocate!% all the init metho! o# NS#$%ect !oe i return se&f. NS#$%ect
!eclare
the metho! mainl$ to etablih the naming convention !ecribe! earlier.
The ;eturne! Object
An init!!! metho! normall$ initiali)e the intance variable o# the receiver an! then return it. It* the
reponibilit$ o# the metho! to return an object that can be ue! &ithout error.
Allocating an! Initiali)ing Object D?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
7o&ever% in ome cae% thi reponibilit$ can mean returning a !i##erent object than the receiver. Aor
e'ample% i# a cla +eep a lit o# name! object% it might provi!e an initWithNa+e: metho! to initiali)e
ne& intance. I# there can be no more than one object per name% initWithNa+e: might re#ue to aign
the ame name to t&o object. :hen a+e! to aign a name to a ne& intance% an! the name i alrea!$
being ue! b$ another object% it might #ree the ne&l$ allocate! intance an! return the other objectGthu
enuring the uni@uene o# the name &hile at the ame time provi!ing &hat &a a+e! #or% an intance &ith
the re@uete! name.
In a #e& cae% it might be impoible #or an init!!! metho! to !o &hat it* a+e! to !o. Aor e'ample% an
init9ro+9i&e: metho! might get the !ata it nee! #rom a #ile pae! a a parameter. I# the #ilename it*
pae! !oen*t correpon! to an actual #ile% it &on*t be able to complete the initiali)ation. In uch a cae%
the
init!!! metho! coul! #ree the receiver an! return ni&% in!icating that the re@uete! object can*t be
create!.
1ecaue an init!!! metho! might return an object other than the ne&l$ allocate! receiver% or even return
ni&% it* important that program ue the value returne! b$ the initiali)ation metho!% not jut that returne!
b$ a&&oc or a&&ocWithPone:. The #ollo&ing co!e i ver$ !angerou% ince it ignore the return o# init.
id an#$%ect 5 [So+eC&ass a&&oc]
[an#$%ect init]
[an#$%ect so+e#ther4essage]
Intea!% to a#el$ initiali)e an object% $ou houl! combine allocation an! initiali)ation meage in one line
o# co!e.
id an#$%ect 5 [[So+eC&ass a&&oc] init]
[an#$%ect so+e#ther4essage]
I# there* a chance that the init!!! metho! might return ni& Eee I7an!ling Initiali)ation AailureJ Epage
-2FF% then $ou houl! chec+ the return value be#ore procee!ing(
id an#$%ect 5 [[So+eC&ass a&&oc] init]
if ( an#$%ect )
[an#$%ect so+e#ther4essage]
e&se
!!!
Implementing an Initiali)er
:hen a ne& object i create!% all bit o# memor$ Ee'cept #or isaFGan! hence the value #or all it intance
variableGare et to '. In ome ituation% thi ma$ be all $ou re@uire &hen an object i initiali)e!L in
man$
other% $ou &ant to provi!e other !e#ault value #or an object* intance variable% or $ou &ant to pa
value
a parameter to the initiali)er. In thee other cae% $ou nee! to &rite a cutom initiali)er. In Objective-C%
cutom initiali)er are ubject to more contraint an! convention than are mot other metho!.
Contraint an! Convention
There are everal contraint an! convention that appl$ to initiali)er metho! that !o not appl$ to other
metho!(
1$ convention% the name o# a cutom initiali)er metho! begin &ith init.
A0 Implementing an Initiali)er
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
?'ample #rom the Aoun!ation #rame&or+ inclu!e initWith9or+at:% initWith#$%ects:% an!
initWith#$%ectsAndLe)s:.
The return t$pe o# an initiali)er metho! houl! be id.
The return t$pe houl! be id becaue id give an in!ication that the cla i purpoel$ not
coni!ere!Gthat the cla i unpeci#ie! an! ubject to change% !epen!ing on conte't o# invocation.
Aor e'ample% NSString provi!e the metho! initWith9or+at:. :hen ent to an intance o#
NS4uta$&eString Ea ubcla o# NSStringF% ho&ever% the meage return an intance o#
NS4uta$&eString% not NSString. E3ee alo% though% the ingleton e'ample given in ICombining
Allocation an! Initiali)ationJ Epage -=F.F
In the implementation o# a cutom initiali)er% $ou mut ultimatel$ invo+e a !esignate! initiali;er.
8eignate! initiali)er are !ecribe! in IThe 8eignate! Initiali)erJ Epage --FL a #ull e'planation o# thi
iue i given in ICoor!inating ClaeJ Epage -<F.
In brie#% i# $ou are implementing a ne& !eignate! initiali)er% it mut invo+e the upercla* !eignate!
initiali)er. I# $ou are implementing an$ other initiali)er% it houl! invo+e it o&n cla* !eignate!
initiali)er% or another o# it o&n initiali)er that ultimatel$ invo+e the !eignate! initiali)er.
1$ !e#ault Euch a &ith NS#$%ectF% the !eignate! initiali)er i init.
Bou houl! aign se&f to the value returne! b$ the initiali)er becaue the initiali)er coul! return an
object !i##erent #rom the one returne! b$ the original receiver.
I# $ou et the value o# an intance variable% $ou t$picall$ !o o uing !irect aignment rather than uing
an acceor metho!.
8irect aignment avoi! the poibilit$ o# triggering un&ante! i!e e##ect in the acceor.
At the en! o# the initiali)er% $ou mut return se&f unle the initiali)er #ail% in &hich cae $ou return
ni&.
Aaile! initiali)er are !icue! in more !etail in I7an!ling Initiali)ation AailureJ Epage -2F.
The #ollo&ing e'ample illutrate the implementation o# a cutom initiali)er #or a cla that inherit #rom
NS#$%ect an! ha an intance variable% creation6ate% that repreent the time &hen the object &a
create!(
- (id)init {
(( Assign se&f to va&ue returned $) superJs designated initia&i@er
(( 6esignated initia&i@er for NS#$%ect is init
se&f 5 [super init]
if (se&f) {
creation6ate 5 [[NS6ate a&&oc] init]
"
return se&f
"
EThe reaon #or uing the if (se&f) pattern i !icue! in I7an!ling Initiali)ation AailureJ Epage -2F.F
Implementing an Initiali)er A1
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
An initiali)er !oen*t nee! to provi!e a parameter #or each variable. Aor e'ample% i# a cla re@uire it
intance
to have a name an! a !ata ource% it might provi!e an initWithNa+e:fro+Q,=: metho!% but et
noneential
intance variable to arbitrar$ value or allo& them to have the null value et b$ !e#ault. It coul! then rel$
on metho! li+e set;na$&ed:% set9riend:% an! set6i+ensions: to mo!i#$ !e#ault value a#ter the
initiali)ation phae ha! been complete!.
The ne't e'ample illutrate the implementation o# a cutom initiali)er that ta+e a ingle parameter. In thi
cae% the cla inherit #rom NSEie8. It ho& that $ou can !o &or+ be#ore invo+ing the uper cla*
!eignate!
initiali)er.
- (id)initWith?+age:(NS?+age *)an?+age {
(( 9ind the si@e for the ne8 instance fro+ the i+age
NSSi@e si@e 5 an?+age!si@e
NS,ect fra+e 5 NS4ake,ect('!'3 '!'3 si@e!8idth3 si@e!height)
(( Assign se&f to va&ue returned $) superJs designated initia&i@er
(( 6esignated initia&i@er for NSEie8 is initWith9ra+e:
se&f 5 [super initWith9ra+e:fra+e]
if (se&f) {
i+age 5 [an?+age retain]
"
return se&f
"
Thi e'ample !oen*t ho& &hat to !o i# there are an$ problem !uring initiali)ationL ho& to han!le uch
problem i !icue! in the ne't ection.
7an!ling Initiali)ation Aailure
In general% i# there i a problem !uring an initiali)ation metho!% $ou houl! call the re&ease metho! on
se&f an! return ni&.
There are t&o main cone@uence o# thi polic$(
An$ object E&hether $our o&n cla% a ubcla% or an e'ternal callerF that receive ni& #rom an
initiali)er
metho! houl! be able to !eal &ith it. In the unli+el$ cae that the caller ha etablihe! an$ e'ternal
re#erence to the object be#ore the call% $ou mut un!o an$ connection.
Bou mut ma+e ure that dea&&oc metho! are a#e in the preence o# partiall$ initiali)e! object.
(ote: Bou houl! call the re&ease metho! on se&f onl$ at the point o# #ailure. I# $ou get ni& bac+
#rom
an invocation o# the upercla* initiali)er% $ou houl! not alo call re&ease. Bou houl! impl$ clean up
an$ re#erence $ou ha! et up that are not !ealt &ith in dea&&oc an! return ni&. Thee tep are t$picall$
han!le! b$ the pattern o# per#orming initiali)ation &ithin a bloc+ !epen!ent on a tet o# the return value o#
the upercla* initiali)erGa een in previou e'ample(
- (id)init {
se&f 5 [super init]
if (se&f) {
creation6ate 5 [[NS6ate a&&oc] init]
"
return se&f
"
A2 Implementing an Initiali)er
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
The #ollo&ing e'ample buil! on that ho&n in IContraint an! ConventionJ Epage -0F to ho& ho& to
han!le an inappropriate value pae! a the parameter(
- (id)initWith?+age:(NS?+age *)an?+age {
if (an?+age 55 ni&) {
[se&f re&ease]
return ni&
"
(( 9ind the si@e for the ne8 instance fro+ the i+age
NSSi@e si@e 5 an?+age!si@e
NS,ect fra+e 5 NS4ake,ect('!'3 '!'3 si@e!8idth3 si@e!height)
(( Assign se&f to va&ue returned $) superJs designated initia&i@er
(( 6esignated initia&i@er for NSEie8 is initWith9ra+e:
se&f 5 [super initWith9ra+e:fra+e]
if (se&f) {
i+age 5 [an?+age retain]
"
return se&f
"
The ne't e'ample illutrate bet practice &here% in the cae o# a problem% there i a poibilit$ o# returning
meaning#ul in#ormation in the #orm o# an NS;rror object returne! b$ re#erence(
- (id)initWithQ,=:(NSQ,= *)aQ,= error:(NS;rror **)error>tr {
se&f 5 [super init]
if (se&f) {
NS6ata *data 5 [[NS6ata a&&oc] initWithContents#fQ,=:aQ,=
options:NSQncached,ead error:error>tr]
if (data 55 ni&) {
(( ?n this case the error o$%ect is created in the NS6ata initia&i@er
[se&f re&ease]
return ni&
"
(( i+p&e+entation continues!!!
Bou houl! t$picall$ not ue e'ception to igni#$ error o# thi ortG#or more in#ormation% ee )rror
*andling
Programming Guide.
Coor!inating Clae
The init!!! metho! a cla !e#ine t$picall$ initiali)e onl$ thoe variable !eclare! in that cla.
Inherite!
intance variable are initiali)e! b$ en!ing a meage to super to per#orm an initiali)ation metho!
!e#ine!
ome&here #arther up the inheritance hierarch$(
- (id)initWithNa+e:(NSString *)string {
se&f 5 [super init]
if (se&f) {
na+e 5 [string cop)]
"
Implementing an Initiali)er A@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
return se&f
"
The meage to super chain together initiali)ation metho! in all inherite! clae. 1ecaue it come
#irt%
it enure that upercla variable are initiali)e! be#ore thoe !eclare! in ubclae. Aor e'ample% a
,ectang&e object mut be initiali)e! a an NS#$%ect% a 7raphic object% an! a Shape object be#ore it*
initiali)e! a a ,ectang&e object.
The connection bet&een the initWithNa+e: metho! illutrate! above an! the inherite! init metho! it
incorporate i illutrate! in Aigure <-1.
3igure @-1 Incorporating an inherite! initiali)ation metho!
Class B
Class A
init
initWithName:
A cla mut alo ma+e ure that all inherite! initiali)ation metho! &or+. Aor e'ample% i# cla A !e#ine
an
init metho! an! it ubcla < !e#ine an initWithNa+e: metho!% a ho&n in Aigure <-1% < mut
alo
ma+e ure that an init meage ucce#ull$ initiali)e < intance. The eaiet &a$ to !o that i to
replace
the inherite! init metho! &ith a verion that invo+e initWithNa+e:(
- init {
return [se&f initWithNa+e:Cdefau&tC]
"
The initWithNa+e: metho! &oul!% in turn% invo+e the inherite! metho!% a ho&n earlier. Aigure <-2
inclu!e the < verion o# init.
AD Implementing an Initiali)er
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
3igure @-2 Covering an inherite! initiali)ation metho!
Class B
Class A
init
init
initWithName:
Covering inherite! initiali)ation metho! ma+e the cla $ou !e#ine more portable to other application. I#
$ou leave an inherite! metho! uncovere!% omeone ele ma$ ue it to pro!uce incorrectl$ initiali)e!
intance
o# $our cla.
The 8eignate! Initiali)er
In the e'ample given in ICoor!inating ClaeJ Epage -<F% initWithNa+e: &oul! be the !esignate!
initiali;er #or it cla Ecla <F. The !eignate! initiali)er i the metho! in each cla that guarantee
inherite!
intance variable are initiali)e! Eb$ en!ing a meage to super to per#orm an inherite! metho!F. It* alo
the metho! that !oe mot o# the &or+% an! the one that other initiali)ation metho! in the ame cla
invo+e. It* a Cocoa convention that the !eignate! initiali)er i al&a$ the metho! that allo& the mot
#ree!om to !etermine the character o# a ne& intance Euuall$ thi i the one &ith the mot parameter% but
not al&a$F.
It* important to +no& the !eignate! initiali)er &hen !e#ining a ubcla. Aor e'ample% cla C% a ubcla
o# <% implement an initWithNa+e:fro+9i&e: metho!. In a!!ition to thi metho!% $ou have to ma+e
ure that the inherite! init an! initWithNa+e: metho! o# cla < alo &or+ #or intance o# C% &hich
$ou
can !o jut b$ covering the < cla* initWithNa+e: metho! &ith a verion that invo+e
initWithNa+e:fro+9i&e:.
- initWithNa+e:(char *)string {
return [se&f initWithNa+e:string fro+9i&e:NQ==]
"
Aor an intance o# the C cla% the inherite! init metho! invo+e thi ne& verion o# initWithNa+e:%
&hich
invo+e initWithNa+e:fro+9i&e:. The relationhip bet&een thee metho! i ho&n in Aigure <-<.
The 8eignate! Initiali)er AA
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
3igure @-@ Covering the !eignate! initiali)er
initWithName:fromFile:
initWithName:
Class B
init
Class C
initWithName:
Thi #igure omit an important !etail. The initWithNa+e:fro+9i&e: metho!% being the !eignate!
initiali)er #or the C cla% en! a meage to super to invo+e an inherite! initiali)ation metho!. 1ut
&hich
o# 1* metho! houl! it invo+e% init or initWithNa+e:O It can*t invo+e init% #or t&o reaon(
Circularit$ &oul! reult Einit invo+e C* initWithNa+e:% &hich invo+e
initWithNa+e:fro+9i&e:%
&hich invo+e init againF.
It &on*t be able to ta+e a!vantage o# the initiali)ation co!e in 1* verion o# initWithNa+e:.
There#ore% initWithNa+e:fro+9i&e: mut invo+e initWithNa+e:(
- initWithNa+e:(char *)string fro+9i&e:(char *)pathna+e {
se&f 5 [super initWithNa+e:string]
if (se&f) {
!!!
"
8eneral principle: The !eignate! initiali)er in a cla mut% through a meage to super% invo+e the
!eignate! initiali)er in a upercla.
8eignate! initiali)er are chaine! to each other through meage to super% &hile other initiali)ation
metho! are chaine! to !eignate! initiali)er through meage to se&f.
Aigure <-. ho& ho& all the initiali)ation metho! in clae A% <% an! C are lin+e!. 2eage to se&f
are
ho&n on the le#t an! meage to super are ho&n on the right.
AE The 8eignate! Initiali)er
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
3igure @-D The initiali)ation chain
initWithName:fromFile:
initWithName:
Class B
Class A
init
init
Class C
initWithName:
"ote that < verion o# init en! a meage to se&f to invo+e the initWithNa+e: metho!.
There#ore%
&hen the receiver i an intance o# the < cla% it invo+e the < verion o# initWithNa+e:% an! &hen the
receiver i an intance o# the C cla% it invo+e the C verion.
Combining Allocation an! Initiali)ation
In Cocoa% ome clae !e#ine creation metho! that combine the t&o tep o# allocating an! initiali)ing to
return ne&% initiali)e! intance o# the cla. Thee metho! are o#ten re#erre! to a convenience
constructors
an! t$picall$ ta+e the #orm I className+++ &here className i the name o# the cla. Aor e'ample%
NSString
ha the #ollo&ing metho! Eamong otherF(
I (id)stringWithCString:(const char *)cString encoding:(NSString;ncoding)enc
I (id)stringWith9or+at:(NSString *)for+at3 !!!
3imilarl$% NSArra) !e#ine the #ollo&ing cla metho! that combine allocation an! initiali)ation(
I (id)arra)
Combining Allocation an! Initiali)ation AF
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
I (id)arra)With#$%ect:(id)an#$%ect
I (id)arra)With#$%ects:(id)first#$%3 !!!
,"portant: Bou mut un!ertan! the memor$ management implication o# uing thee metho! i# $ou !o
not ue garbage collection Eee I2emor$ 2anagementJ Epage 1-FF. Bou mut rea! Memory
Management
Programming Guide to un!ertan! the polic$ that applie to thee convenience contructor.
The return t$pe o# convenience contructor i id #or the ame reaon it i id #or initiali)er metho!% a
!icue! in IContraint an! ConventionJ Epage -0F.
2etho! that combine allocation an! initiali)ation are particularl$ valuable i# the allocation mut omeho&
be in#orme! b$ the initiali)ation. Aor e'ample% i# the !ata #or the initiali)ation i ta+en #rom a #ile% an! the
#ile
might contain enough !ata to initiali)e more than one object% it &oul! be impoible to +no& ho& man$
object to allocate until the #ile i opene!. In thi cae% $ou might implement a &ist9ro+9i&e: metho!
that
ta+e the name o# the #ile a a parameter. It &oul! open the #ile% ee ho& man$ object to allocate% an!
create
a =ist object large enough to hol! all the ne& object. It &oul! then allocate an! initiali)e the object
#rom
!ata in the #ile% put them in the lit% an! #inall$ return the lit.
It alo ma+e ene to combine allocation an! initiali)ation in a ingle metho! i# $ou &ant to avoi! the tep
o# blin!l$ allocating memor$ #or a ne& object that $ou might not ue. A mentione! in IThe ;eturne!
ObjectJ Epage .,F% an init!!! metho! might ometime ubtitute another object #or the receiver. Aor
e'ample% &hen initWithNa+e: i pae! a name that* alrea!$ ta+en% it might #ree the receiver an! in it
place return the object that &a previoul$ aigne! the name. Thi mean% o# coure% that an object i
allocate! an! #ree! imme!iatel$ &ithout ever being ue!.
I# the co!e that !etermine &hether the receiver houl! be initiali)e! i place! ini!e the metho! that !oe
the allocation intea! o# ini!e init!!!% $ou can avoi! the tep o# allocating a ne& intance &hen one
in*t
nee!e!.
In the #ollo&ing e'ample% the so&oist metho! enure that there* no more than one intance o# the
So&oist cla. It allocate an! initiali)e a ingle hare! intance(
I (So&oist *)so&oist {
static So&oist *instance 5 ni&
if ( instance 55 ni& ) {
instance 5 [[se&f a&&oc] init]
"
return instance
"
"otice that in thi cae the return t$pe i So&oist *. 1ecaue thi metho! return a ingleton hare
intance%
trong t$ping i appropriateGthere i no e'pectation that thi metho! &ill be overri!!en.
A8 Combining Allocation an! Initiali)ation
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* @
Allocating an! Initiali)ing Object
Protocol !eclare metho! that can be implemente! b$ an$ cla. Protocol are ue#ul in at leat three
ituation(
To !eclare metho! that other are e'pecte! to implement
To !eclare the inter9ace to an object &hile concealing it cla
To capture imilaritie among clae that are not hierarchicall$ relate!
8eclaring Inter#ace #or Other to Implement
Cla an! categor$ inter#ace !eclare metho! that are aociate! &ith a particular claGmainl$ metho!
that the cla implement. In#ormal an! #ormal protocols% on the other han!% !eclare metho! that are
in!epen!ent o# an$ peci#ic cla% but &hich an$ cla% an! perhap man$ clae% might implement.
A protocol i impl$ a lit o# metho! !eclaration% unattache! to a cla !e#inition. Aor e'ample% thee
metho!
that report uer action on the moue coul! be gathere! into a protocol(
- (void)+ouse6o8n:(NS;vent *)the;vent
- (void)+ouse6ragged:(NS;vent *)the;vent
- (void)+ouseQp:(NS;vent *)the;vent
An$ cla that &ante! to repon! to moue events coul! a!opt the protocol an! implement it metho!.
Protocol #ree metho! !eclaration #rom !epen!enc$ on the cla hierarch$% o the$ can be ue! in &a$
that clae an! categorie cannot. Protocol lit metho! that are Eor ma$ beF implemente! ome&here%
but the i!entit$ o# the cla that implement them i not o# interet. :hat i o# interet i &hether or not a
particular cla con9or"s to the protocolG&hether it ha implementation o# the metho! the protocol
!eclare. Thu object can be groupe! into t$pe not jut on the bai o# imilaritie reulting #rom
inheriting
#rom the ame cla% but alo on the bai o# their imilarit$ in con#orming to the ame protocol. Clae in
unrelate! branche o# the inheritance hierarch$ might be t$pe! ali+e becaue the$ con#orm to the ame
protocol.
Protocol can pla$ a igni#icant role in object-oriente! !eign% epeciall$ &hen a project i !ivi!e! among
man$ implementor or it incorporate object !evelope! in other project. Cocoa o#t&are ue protocol
heavil$ to upport interproce communication through Objective-C meage.
7o&ever% an Objective-C program !oen*t nee! to ue protocol. 4nli+e cla !e#inition an! meage
e'preion% the$*re optional. 3ome Cocoa #rame&or+ ue themL ome !on*t. It all !epen! on the ta+ at
han!.
8eclaring Inter#ace #or Other to Implement A?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
2etho! #or Other to Implement
I# $ou +no& the cla o# an object% $ou can loo+ at it inter#ace !eclaration Ean! the inter#ace !eclaration
o#
the clae it inherit #romF to #in! &hat meage it repon! to. Thee !eclaration a!vertie the meage
it can receive. Protocol provi!e a &a$ #or it to alo a!vertie the meage it en!.
Communication &or+ both &a$L object en! meage a &ell a receive them. Aor e'ample% an object
might !elegate reponibilit$ #or a certain operation to another object% or it ma$ on occaion impl$ nee!
to a+ another object #or in#ormation. In ome cae% an object might be &illing to noti#$ other object o# it
action o that the$ can ta+e &hatever collateral meaure might be re@uire!.
I# $ou !evelop the cla o# the en!er an! the cla o# the receiver a part o# the ame project Eor i# omeone
ele ha upplie! $ou &ith the receiver an! it inter#ace #ileF% thi communication i eail$ coor!inate!. The
en!er impl$ import the inter#ace #ile o# the receiver. The importe! #ile !eclare the metho! elector the
en!er ue in the meage it en!.
7o&ever% i# $ou !evelop an object that en! meage to object that aren*t $et !e#ine!Gobject that
$ou*re
leaving #or other to implementG$ou &on*t have the receiver* inter#ace #ile. Bou nee! another &a$ to
!eclare the metho! $ou ue in meage but !on*t implement. A protocol erve thi purpoe. It in#orm
the compiler about metho! the cla ue an! alo in#orm other implementor o# the metho! the$ nee!
to !e#ine to have their object &or+ &ith $our.
3uppoe% #or e'ample% that $ou !evelop an object that a+ #or the aitance o# another object b$ en!ing
it he&p#ut: an! other meage. Bou provi!e an assistant intance variable to recor! the outlet #or
thee
meage an! !e#ine a companion metho! to et the intance variable. Thi metho! let other object
regiter
themelve a potential recipient o# $our object* meage(
- setAssistant:an#$%ect
{
assistant 5 an#$%ect
"
Then% &henever a meage i to be ent to the assistant% a chec+ i ma!e to be ure that the receiver
implement a metho! that can repon!(
- (<##=)doWork
{
!!!
if ( [assistant responds1oSe&ector:@se&ector(he&p#ut:)] ) {
[assistant he&p#ut:se&f]
return :;S
"
return N#
"
1ecaue% at the time $ou &rite thi co!e% $ou can*t +no& &hat +in! o# object might regiter itel# a the
assistant% $ou can onl$ !eclare a protocol #or the he&p#ut: metho!L $ou can*t import the inter#ace #ile
o# the cla that implement it.
E0 2etho! #or Other to Implement
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
8eclaring Inter#ace #or Anon$mou Object
A protocol can be ue! to !eclare the metho! o# an anon:"ous object% an object o# un+no&n cla. An
anon$mou object ma$ repreent a ervice or han!le a limite! et o# #unction% epeciall$ &hen onl$ one
object o# it +in! i nee!e!. EObject that pla$ a #un!amental role in !e#ining an application* architecture
an! object that $ou mut initiali)e be#ore uing are not goo! can!i!ate #or anon$mit$.F
Object are not anon$mou to their !eveloper% o# coure% but the$ are anon$mou &hen the !eveloper
upplie them to omeone ele. Aor e'ample% coni!er the #ollo&ing ituation(
3omeone &ho upplie a #rame&or+ or a uite o# object #or other to ue can inclu!e object that are
not i!enti#ie! b$ a cla name or an inter#ace #ile. Lac+ing the name an! cla inter#ace% uer have no
&a$ o# creating intance o# the cla. Intea!% the upplier mut provi!e a rea!$-ma!e intance. T$picall$%
a metho! in another cla return a uable object(
id for+atter 5 [receiver for+attingService]
The object returne! b$ the metho! i an object &ithout a cla i!entit$% at leat not one the upplier i
&illing to reveal. Aor it to be o# an$ ue at all% the upplier mut be &illing to i!enti#$ at leat ome o#
the meage that it can repon! to. The meage are i!enti#ie! b$ aociating the object &ith a lit o#
metho! !eclare! in a protocol.
Bou can en! Objective-C meage to re"ote objectsGobject in other application. EI;emote
2eagingJ in the Objective-C Runtime Programming Guide% !icue thi poibilit$ in more
!etail.F
?ach application ha it o&n tructure% clae% an! internal logic. 1ut $ou !on*t nee! to +no& ho&
another application &or+ or &hat it component are to communicate &ith it. A an outi!er% all $ou
nee! to +no& i &hat meage $ou can en! Ethe protocolF an! &here to en! them Ethe receiverF.
An application that publihe one o# it object a a potential receiver o# re"ote "essages mut alo
publih a protocol !eclaring the metho! the object &ill ue to repon! to thoe meage. It !oen*t
have to !icloe an$thing ele about the object. The en!ing application !oen*t nee! to +no& the cla
o# the object or ue the cla in it o&n !eign. All it nee! i the protocol.
Protocol ma+e anon$mou object poible. :ithout a protocol% there &oul! be no &a$ to !eclare an
inter#ace to an object &ithout i!enti#$ing it cla.
(ote: ?ven though the upplier o# an anon$mou object !oen*t reveal it cla% the object itel# reveal it
at runtime. A cla meage return the anon$mou object* cla. 7o&ever% there* uuall$ little point in
!icovering thi e'tra in#ormationL the in#ormation in the protocol i u##icient.
"onhierarchical 3imilaritie
I# more than one cla implement a et o# metho!% thoe clae are o#ten groupe! un!er an abtract cla
that !eclare the metho! the$ have in common. ?ach ubcla can reimplement the metho! in it o&n
&a$% but the inheritance hierarch$ an! the common !eclaration in the abtract cla capture the eential
imilarit$ bet&een the ubclae.
8eclaring Inter#ace #or Anon$mou Object E1
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
7o&ever% ometime it* not poible to group common metho! in an abtract cla. Clae that are
unrelate!
in mot repect might neverthele nee! to implement ome imilar metho!. Thi limite! imilarit$ ma$
not juti#$ a hierarchical relationhip. Aor e'ample% $ou might &ant to a!! upport #or creating H2L
repreentation o# object in $our application an! #or initiali)ing object #rom an H2L repreentation(
- (NS.4=;&e+ent *).4=,epresentation
- init9ro+.4=,epresentation:(NS.4=;&e+ent *)2+&String
Thee metho! coul! be groupe! into a protocol an! the imilarit$ bet&een implementing clae
accounte!
#or b$ noting that the$ all con#orm to the ame protocol.
Object can be t$pe! b$ thi imilarit$ Ethe protocol the$ con#orm toF% rather than b$ their cla. Aor
e'ample%
an NS4atri2 intance mut communicate &ith the object that repreent it cell. The matri' coul! re@uire
each o# thee object to be a +in! o# NSCe&& Ea t$pe bae! on claF an! rel$ on the #act that all object
that
inherit #rom the NSCe&& cla have the metho! nee!e! to repon! to NS4atri2 meage. Alternativel$%
the NS4atri2 object coul! re@uire object repreenting cell to have metho! that can repon! to a
particular
et o# meage Ea t$pe bae! on protocolF. In thi cae% the NS4atri2 object &oul!n*t care &hat cla a
cell
object belonge! to% jut that it implemente! the metho!.
Aormal Protocol
The Objective-C language provi!e a &a$ to #ormall$ !eclare a lit o# metho! Einclu!ing !eclare!
propertieF
a a protocol. 3or"al protocols are upporte! b$ the language an! the runtime $tem. Aor e'ample% the
compiler can chec+ #or t$pe bae! on protocol% an! object can intropect at runtime to report &hether
or not the$ con#orm to a protocol.
8eclaring a Protocol
Bou !eclare #ormal protocol &ith the @protoco& !irective(
@protoco& >rotoco&Na+e
+ethod dec&arations
@end
Aor e'ample% $ou coul! !eclare an H2L repreentation protocol li+e thi(
@protoco& 4).4=Support
- init9ro+.4=,epresentation:(NS.4=;&e+ent *).4=;&e+ent
- (NS.4=;&e+ent *).4=,epresentation
@end
4nli+e cla name% protocol name !on*t have global viibilit$. The$ live in their o&n namepace.
Optional Protocol 2etho!
Protocol metho! can be mar+e! a optional uing the @optiona& +e$&or!. Correpon!ing to the
@optiona&
mo!al +e$&or!% there i a @reKuired +e$&or! to #ormall$ !enote the emantic o# the !e#ault behavior.
Bou can ue @optiona& an! @reKuired to partition $our protocol into ection a $ou ee #it. I# $ou !o
not
peci#$ an$ +e$&or!% the !e#ault i @reKuired.
E2 Aormal Protocol
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
@protoco& 4)>rotoco&
- (void)reKuired4ethod
@optiona&
- (void)an#ptiona&4ethod
- (void)another#ptiona&4ethod
@reKuired
- (void)another,eKuired4ethod
@end
(ote: In 2ac O3 H v10.-% protocol cannot inclu!e optional !eclare! propertie. Thi contraint i
remove!
in 2ac O3 H v10.0 an! later.
In#ormal Protocol
In a!!ition to #ormal protocol% $ou can alo !e#ine an in9or"al protocol b$ grouping the metho! in a
categor$ !eclaration(
@interface NS#$%ect ( 4).4=Support )
- init9ro+.4=,epresentation:(NS.4=;&e+ent *).4=;&e+ent
- (NS.4=;&e+ent *).4=,epresentation
@end
In#ormal protocol are t$picall$ !eclare! a categorie o# the NS#$%ect cla% becaue that broa!l$
aociate
the metho! name &ith an$ cla that inherit #rom NS#$%ect. 1ecaue all clae inherit #rom the root
cla%
the metho! aren*t retricte! to an$ part o# the inheritance hierarch:. EIt i alo poible to !eclare an
in#ormal protocol a a categor$ o# another cla to limit it to a certain branch o# the inheritance hierarch$%
but there i little reaon to !o o.F
:hen ue! to !eclare a protocol% a categor$ inter#ace !oen*t have a correpon!ing implementation.
Intea!%
clae that implement the protocol !eclare the metho! again in their o&n inter#ace #ile an! !e#ine them
along &ith other metho! in their i"ple"entation #ile.
An in#ormal protocol ben! the rule o# categor$ !eclaration to lit a group o# metho! but not aociate
them &ith an$ particular cla or implementation.
1eing in#ormal% protocol !eclare! in categorie !on*t receive much language upport. There* no t$pe
chec+ing at compile time nor a chec+ at runtime to ee &hether an object con#orm to the protocol. To get
thee bene#it% $ou mut ue a #ormal protocol. An in#ormal protocol ma$ be ue#ul &hen all the metho!
are optional% uch a #or a !elegate% but Ein 2ac O3 H v10.- an! laterF it i t$picall$ better to ue a #ormal
protocol &ith optional metho!.
In#ormal Protocol E@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
Protocol Object
5ut a clae are repreente! at runtime b$ cla object an! metho! b$ elector co!e% #ormal protocol
are repreente! b$ a pecial !ata t$peGintance o# the >rotoco& cla. 3ource co!e that !eal &ith a
protocol Eother than to ue it in a t$pe peci#icationF mut re#er to the correpon!ing protocol object.
In man$ &a$% protocol are imilar to cla !e#inition. The$ both !eclare metho!% an! at runtime the$*re
both repreente! b$ objectGclae b$ intance o# C&ass an! protocol b$ intance o# >rotoco&. Li+e
cla object% protocol object are create! automaticall$ #rom the !e#inition an! !eclaration #oun! in
ource
co!e an! are ue! b$ the runtime $tem. The$*re not allocate! an! initiali)e! in program ource co!e.
3ource co!e can re#er to a protocol object uing the @protoco&() !irectiveGthe ame !irective that
!eclare
a protocol% e'cept that here it ha a et o# trailing parenthee. The parenthee encloe the protocol name(
>rotoco& *+).4=Support>rotoco& 5 @protoco&(4).4=Support)
Thi i the onl$ &a$ that ource co!e can conjure up a protocol object. 4nli+e a cla name% a protocol
name
!oen*t !eignate the objectGe'cept ini!e @protoco&().
The compiler create a protocol object #or each protocol !eclaration it encounter% but onl$ i# the protocol
i alo(
A!opte! b$ a cla% or
;e#erre! to ome&here in ource co!e Euing @protoco&()F
Protocol that are !eclare! but not ue! Ee'cept #or t$pe chec+ing a !ecribe! belo&F aren*t repreente!
b$ protocol object at runtime.
A!opting a Protocol
A!opting a protocol i imilar in ome &a$ to !eclaring a upercla. 1oth aign metho! to the cla.
The
upercla !eclaration aign it inherite! metho!L the protocol aign it metho! !eclare! in the protocol
lit. A cla i ai! to a!opt a #ormal protocol i# in it !eclaration it lit the protocol &ithin angle brac+et
a#ter the upercla name(
@interface C&assNa+e : ?tsSuperc&ass N protoco& &ist O
Categorie a!opt protocol in much the ame &a$(
@interface C&assNa+e ( Categor)Na+e ) N protoco& &ist O
A cla can a!opt more than one protocolL name in the protocol lit are eparate! b$ comma.
@interface 9or+atter : NS#$%ect N 9or+atting3 >rettif)ing O
A cla or categor$ that a!opt a protocol mut implement all the re@uire! metho! the protocol !eclare%
other&ie the compiler iue a &arning. The Aormatter cla above &oul! !e#ine all the re@uire! metho!
!eclare! in the t&o protocol it a!opt% in a!!ition to an$ it might have !eclare! itel#.
ED Protocol Object
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
A cla or categor$ that a!opt a protocol mut import the hea!er #ile &here the protocol i !eclare!. The
metho! !eclare! in the a!opte! protocol are not !eclare! ele&here in the cla or categor$ inter#ace.
It* poible #or a cla to impl$ a!opt protocol an! !eclare no other metho!. Aor e'ample% the #ollo&ing
cla !eclaration a!opt the 9or+atting an! >rettif)ing protocol% but !eclare no intance variable
or metho! o# it o&n(
@interface 9or+atter : NS#$%ect N 9or+atting3 >rettif)ing O
@end
Con#orming to a Protocol
A cla i ai! to con9or" to a #ormal protocol i# it a!opt the protocol or inherit #rom another cla that
a!opt it. An intance o# a cla i ai! to con#orm to the ame et o# protocol it cla con#orm to.
1ecaue a cla mut implement all the re@uire! metho! !eclare! in the protocol it a!opt% a$ing that a
cla or an intance con#orm to a protocol i e@uivalent to a$ing that it ha in it repertoire all the metho!
the protocol !eclare.
It* poible to chec+ &hether an object con#orm to a protocol b$ en!ing it a confor+s1o>rotoco&:
meage.
if ( G [receiver confor+s1o>rotoco&:@protoco&(4).4=Support)] ) {
(( #$%ect does not confor+ to 4).4=Support protoco&
(( ?f )ou are e2pecting receiver to i+p&e+ent +ethods dec&ared in the
(( 4).4=Support protoco&3 this is pro$a$&) an error
"
E"ote that there i alo a cla metho! &ith the ame nameGconfor+s1o>rotoco&:.F
The confor+s1o>rotoco&: tet i li+e the responds1oSe&ector: tet #or a ingle metho!% e'cept
that
it tet &hether a protocol ha been a!opte! Ean! preumabl$ all the metho! it !eclare implemente!F
rather than jut &hether one particular metho! ha been implemente!. 1ecaue it chec+ #or all the metho!
in the protocol% confor+s1o>rotoco&: can be more e##icient than responds1oSe&ector:.
The confor+s1o>rotoco&: tet i alo li+e the isLind#fC&ass: tet% e'cept that it tet #or a t$pe
bae!
on a protocol rather than a t$pe bae! on the inheritance hierarch$.
T$pe Chec+ing
T$pe !eclaration #or object can be e'ten!e! to inclu!e #ormal protocol. Protocol thu o##er the
poibilit$
o# another level o# t$pe chec+ing b$ the compiler% one that* more abtract ince it* not tie! to particular
implementation.
In a t$pe !eclaration% protocol name are lite! bet&een angle brac+et a#ter the t$pe name(
- (id N9or+attingO)for+attingService
id N4).4=SupportO an#$%ect
Con#orming to a Protocol EA
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
5ut a tatic t$ping permit the compiler to tet #or a t$pe bae! on the cla hierarch$% thi $nta' permit
the compiler to tet #or a t$pe bae! on con#ormance to a protocol.
Aor e'ample% i# 9or+atter i an abtract cla% the !eclaration
9or+atter *an#$%ect
group all object that inherit #rom Aormatter into a t$pe an! permit the compiler to chec+ aignment
againt that t$pe.
3imilarl$% the !eclaration
id N9or+attingO an#$%ect
group all object that con#orm to the Aormatting protocol into a t$pe% regar!le o# their poition in the
cla hierarch$. The compiler can ma+e ure onl$ object that con#orm to the protocol are aigne! to the
t$pe.
In each cae% the t$pe group imilar objectGeither becaue the$ hare a common inheritance% or becaue
the$ converge on a common et o# metho!.
The t&o t$pe can be combine! in a ingle !eclaration(
9or+atter N9or+attingO *an#$%ect
Protocol can*t be ue! to t$pe cla object. Onl$ intance can be taticall$ t$pe! to a protocol% jut a
onl$
intance can be taticall$ t$pe! to a cla. E7o&ever% at runtime% both clae an! intance repon! to a
confor+s1o>rotoco&: meage.F
Protocol :ithin Protocol
One protocol can incorporate other protocol uing the ame $nta' that clae ue to a!opt a protocol(
@protoco& >rotoco&Na+e N protoco& &ist O
All the protocol lite! bet&een angle brac+et are coni!ere! part o# the ProtocolName protocol. Aor
e'ample%
i# the >aging protocol incorporate the 9or+atting protocol
@protoco& >aging N 9or+atting O
an$ object that con#orm to the >aging protocol alo con#orm to 9or+atting. T$pe !eclaration uch a
id N>agingO so+e#$%ect
an! confor+s1o>rotoco&: meage uch a
if ( [another#$%ect confor+s1o>rotoco&:@protoco&(>aging)] )
!!!
nee! to mention onl$ the >aging protocol to tet #or con#ormance to 9or+atting a &ell.
EE Protocol :ithin Protocol
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
:hen a cla a!opt a protocol% it mut implement the re@uire! metho! the protocol !eclare% a
mentione!
earlier. In a!!ition% it mut con#orm to an$ protocol the a!opte! protocol incorporate. I# an incorporate!
protocol incorporate till other protocol% the cla mut alo con#orm to them. A cla can con#orm to an
incorporate! protocol uing either o# thee techni@ue(
Implementing the metho! the protocol !eclare
Inheriting #rom a cla that a!opt the protocol an! implement the metho!
3uppoe% #or e'ample% that the >ager cla a!opt the >aging protocol. I# >ager i a ubcla o#
NS#$%ect
a ho&n here(
@interface >ager : NS#$%ect N >aging O
it mut implement all the >aging metho!% inclu!ing thoe !eclare! in the incorporate! 9or+atting
protocol. It a!opt the 9or+atting protocol along &ith >aging.
On the other han!% i# >ager i a ubcla o# 9or+atter Ea cla that in!epen!entl$ a!opt the
9or+atting
protocolF a ho&n here(
@interface >ager : 9or+atter N >aging O
it mut implement all the metho! !eclare! in the >aging protocol proper% but not thoe !eclare! in
9or+atting. >ager inherit con#ormance to the 9or+atting protocol #rom 9or+atter.
"ote that a cla can con#orm to a protocol &ithout #ormall$ a!opting it% impl$ b$ implementing the
metho!
!eclare! in the protocol.
;e#erring to Other Protocol
:hen &or+ing on comple' application% $ou occaionall$ #in! $ourel# &riting co!e that loo+ li+e thi(
Mi+port C<!hC
@protoco& A
- foo:(id N<O)an#$%ect
@end
&here protocol < i !eclare! li+e thi(
Mi+port CA!hC
@protoco& <
- $ar:(id NAO)an#$%ect
@end
In uch a ituation% circularit$ reult an! neither #ile &ill compile correctl$. To brea+ thi recurive c$cle%
$ou
mut ue the @protoco& !irective to ma+e a #or&ar! re#erence to the nee!e! protocol intea! o# importing
the inter#ace #ile &here the protocol i !e#ine!(
@protoco& <
@protoco& A
;e#erring to Other Protocol EF
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
- foo:(id N<O)an#$%ect
@end
"ote that uing the @protoco& !irective in thi manner impl$ in#orm the compiler that < i a protocol
to
be !e#ine! later. It !oen*t import the inter#ace #ile &here protocol < i !e#ine!.
E8 ;e#erring to Other Protocol
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* D
Protocol
The Objective-C !eclare! propertie #eature provi!e a imple &a$ to !eclare an! implement an object*
acceor metho!.
Overvie&
There are t&o apect to thi language #eature( the $ntactic element $ou ue to peci#$ an! optionall$
$nthei)e !eclare! propertie% an! a relate! $ntactic element that i !ecribe! in I8ot 3$nta'J Epage 1,F.
Bou t$picall$ acce an object* propertie Ein the ene o# it attribute an! relationhipF through a pair o#
acceor Egetter6etterF metho!. 1$ uing acceor metho!% $ou a!here to the principle o# encapsulation
Eee I2echanim O# AbtractionJ in Object-Oriented Programming with Objective-CF. Bou can
e'ercie tight
control o# the behavior o# the getter6etter pair an! the un!erl$ing tate management &hile client o# the
API remain inulate! #rom the implementation change.
Although uing acceor metho! ha igni#icant a!vantage% &riting acceor metho! i neverthele a
te!iou proceGparticularl$ i# $ou have to &rite co!e to upport both garbage-collecte! an!
re#erence-counte! environment. 2oreover% apect o# the propert$ that ma$ be important to conumer
o# the API are le#t obcure!Guch a &hether the acceor metho! are threa!-a#e or &hether ne& value
are copie! &hen et.
8eclare! propertie a!!re the problem &ith tan!ar! acceor metho! b$ provi!ing the #ollo&ing
#eature(
The propert$ !eclaration provi!e a clear% e'plicit peci#ication o# ho& the acceor metho! behave.
The compiler can $nthei)e acceor metho! #or $ou% accor!ing to the peci#ication $ou provi!e in the
!eclaration. Thi mean $ou have le co!e to &rite an! maintain.
Propertie are repreente! $ntacticall$ a i!enti#ier an! are cope!% o the compiler can !etect ue o#
un!eclare! propertie.
Propert$ 8eclaration an! Implementation
There are t&o part to a !eclare! propert$% it !eclaration an! it implementation.
Overvie& E?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
Propert$ 8eclaration
A propert$ !eclaration begin &ith the +e$&or! @propert). @propert) can appear an$&here in the
metho!
!eclaration lit #oun! in the @interface bloc+ o# a cla. @propert) can alo appear in the !eclaration
o#
a protocol or categor$.
@propert)(attri$utes) t)pe na+e
The @propert) !irective !eclare a propert$. An optional parenthei)e! et o# attribute provi!e
a!!itional
!etail about the torage emantic an! other behavior o# the propert$Gee IPropert$ 8eclaration
AttributeJ Epage =0F #or poible value. Li+e an$ other Objective-C t$pe% each propert$ ha a t$pe
peci#ication
an! a name.
Liting --1 illutrate the !eclaration o# a imple propert$.
Listing A-1 8eclaring a imple propert$
@interface 4)C&ass : NS#$%ect
{
f&oat va&ue
"
@propert) f&oat va&ue
@end
Bou can thin+ o# a propert$ !eclaration a being e@uivalent to !eclaring t&o acceor metho!. Thu
@propert) f&oat va&ue
i e@uivalent to(
- (f&oat)va&ue
- (void)setEa&ue:(f&oat)ne8Ea&ue
A propert$ !eclaration% ho&ever% provi!e a!!itional in#ormation about ho& the acceor metho! are
implemente! Ea !ecribe! in IPropert$ 8eclaration AttributeJ Epage =0FF.
Propert$ 8eclaration Attribute
Bou can !ecorate a propert$ &ith attribute b$ uing the #orm @propert)(attri$ute [3
attri$ute-3
!!!]). Li+e metho!% propertie are cope! to their encloing inter#ace !eclaration. Aor propert$
!eclaration
that ue a comma !elimite! lit o# variable name% the propert$ attribute appl$ to all o# the name!
propertie.
I# $ou ue the @s)nthesi@e !irective to tell the compiler to create the acceor metho!% the co!e it
generate
matche the peci#ication given b$ the +e$&or!. I# $ou implement the acceor metho! $ourel#% $ou
houl!
enure that it matche the peci#ication E#or e'ample% i# $ou peci#$ cop) $ou mut ma+e ure that $ou !o
cop$ the input value in the etter metho!F.
Acceor 2etho! "ame
The !e#ault name #or the getter an! etter metho! aociate! &ith a propert$ are (ro(ertyName an!
setPro(ertyName: repectivel$G#or e'ample% given a propert$ I#ooJ% the acceor &oul! be foo
an!
set9oo:. The #ollo&ing attribute allo& $ou to peci#$ cutom name intea!. The$ are both optional an!
can appear &ith an$ other attribute Ee'cept #or readon&) in the cae o# setter5F.
F0 Propert$ 8eclaration an! Implementation
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
getter5getterNa+e
3peci#ie the name o# the get acceor #or the propert$. The getter mut return a t$pe matching the
propert$* t$pe an! ta+e no parameter.
setter5setterNa+e
3peci#ie the name o# the et acceor #or the propert$. The etter metho! mut ta+e a ingle parameter
o# a t$pe matching the propert$* t$pe an! mut return void.
I# $ou peci#$ that a propert$ i readon&) an! alo peci#$ a etter &ith setter5% $ou get a compiler
&arning.
T$picall$ $ou houl! peci#$ acceor metho! name that are +e$-value co!ing compliant Eee %ey-&alue
Coding Programming GuideFGa common reaon #or uing the getter !ecorator i to a!here to the
isPro(ertyName convention #or 1oolean value.
:ritabilit$
Thee attribute peci#$ &hether or not a propert$ ha an aociate! et acceor. The$ are mutuall$
e'cluive.
read8rite
In!icate that the propert$ houl! be treate! a rea!6&rite. Thi attribute i the !e#ault.
1oth a getter an! etter metho! are re@uire! in the @i+p&e+entation bloc+. I# $ou ue the
@s)nthesi@e !irective in the implementation bloc+% the getter an! etter metho! are $nthei)e!.
readon&)
In!icate that the propert$ i rea!-onl$.
I# $ou peci#$ readon&)% onl$ a getter metho! i re@uire! in the @i+p&e+entation bloc+. I# $ou ue
the @s)nthesi@e !irective in the implementation bloc+% onl$ the getter metho! i $nthei)e!.
2oreover% i# $ou attempt to aign a value uing the !ot $nta'% $ou get a compiler error.
3etter 3emantic
Thee attribute peci#$ the emantic o# a et acceor. The$ are mutuall$ e'cluive.
assign
3peci#ie that the etter ue imple aignment. Thi attribute i the !e#ault.
Bou t$picall$ ue thi attribute #or calar t$pe uch a NS?nteger an! C7,ect% or Ein a
re#erence-counte! environmentF #or object $ou !on*t o&n% uch a !elegate.
retain an! assign are e##ectivel$ the ame in a garbage-collecte! environment.
retain
3peci#ie that retain houl! be invo+e! on the object upon aignment. EThe !e#ault i assign.F
The previou value i ent a re&ease meage.
Prior to 2ac O3 H v10.0% thi attribute i vali! onl$ #or Objective-C object t$pe Eo $ou cannot peci#$
retain #or Core Aoun!ation objectGee ICore Aoun!ationJ Epage ==FF.
In 2ac O3 H v10.0 an! later% $ou can ue the **attri$ute** +e$&or! to peci#$ that a Core
Aoun!ation propert$ houl! be treate! li+e an Objective-C object #or memor$ management(
@propert)(retain) **attri$ute**((NS#$%ect)) C96ictionar),ef +)6ictionar)
Propert$ 8eclaration an! Implementation F1
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
cop)
3peci#ie that a cop$ o# the object houl! be ue! #or aignment. EThe !e#ault i assign.F
The previou value i ent a re&ease meage.
The cop$ i ma!e b$ invo+ing the cop) metho!. Thi attribute i vali! onl$ #or object t$pe% &hich
mut implement the NSCop)ing protocol. Aor #urther !icuion% ee ICop$J Epage =-F.
8i##erent contraint appl$ !epen!ing on &hether or not $ou ue garbage collection(
I# $ou !o not ue garbage collection% #or object propertie $ou mut e'plicitl$ peci#$ one o# assign%
retain% or cop)Gother&ie $ou get a compiler &arning. EThi contraint encourage $ou to thin+ about
&hat memor$ management behavior $ou &ant an! to t$pe the behavior e'plicitl$.F
To !eci!e &hich $ou houl! chooe% $ou nee! to un!ertan! Cocoa memor$ management polic$ Eee
Memory Management Programming GuideF.
I# $ou ue garbage collection% $ou !onMt get a &arning i# $ou ue the !e#ault Ethat i% i# $ou !on*t peci#$
an$ o# assign% retain% or cop)F unle the propert$M t$pe i a cla that con#orm to NSCop)ing. The
!e#ault i uuall$ &hat $ou &antL i# the propert$ t$pe can be copie!% ho&ever% to preerve encapulation
$ou o#ten &ant to ma+e a private cop$ o# the object.
Atomicit$
Bou can ue thi attribute to peci#$ that acceor metho! are not atomic. EThere i no +e$&or! to !enote
atomic.F
nonato+ic
3peci#ie that acceor are nonatomic. "y default, accessors are atomic+
Propertie are atomic b$ !e#ault o that $nthei)e! acceor provi!e robut acce to propertie in a
multithrea!e! environmentGthat i% the value returne! #rom the getter or et via the etter i al&a$ #ull$
retrieve! or et regar!le o# &hat other threa! are e'ecuting concurrentl$. Aor more !etail% ee
IPer#ormance
an! Threa!ingJ Epage =,F.
I# $ou peci#$ retain or cop) an! !o not peci#$ nonato+ic% then in a re#erence-counte! environment%
a
$nthei)e! get acceor #or an object propert$ ue a loc+ an! retain an! autoreleae the returne!
valueGthe implementation &ill be imilar to the #ollo&ing(
[*interna& &ock] (( &ock using an o$%ect-&eve& &ock
id resu&t 5 [[va&ue retain] autore&ease]
[*interna& un&ock]
return resu&t
I# $ou peci#$ nonato+ic% a $nthei)e! acceor #or an object propert$ impl$ return the value !irectl$.
2ar+up an! 8eprecation
Propertie upport the #ull range o# C-t$le !ecorator. Propertie can be !eprecate! an! upport
**attri$ute** t$le mar+up(
@propert) C79&oat 2
AEA?=A<=;*4AC*#S*.*E;,S?#N*B'*B*AN6*=A1;,*<Q1*6;>,;CA1;6*?N*4AC*#S*.*E;,S?#N*B'*H
@propert) C79&oat ) **attri$ute**((!!!))
F2 Propert$ 8eclaration an! Implementation
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
I# $ou &ant to peci#$ that a propert$ i an ,nter9ace 2uil!er outlet% $ou can ue the ?<#ut&et
i!enti#ier(
@propert) (nonato+ic3 retain) ?<#ut&et NS<utton *+)<utton
?<#ut&et i not% though% a #ormal part o# the lit o# attribute.
I# $ou ue garbage collection% $ou can ue the torage mo!i#ier **8eak an! **strong in a propert$*
!eclaration(
@propert) (nonato+ic3 retain) **8eak =ink *parent
1ut again% torage mo!i#ier are not a #ormal part o# the lit o# attribute.
Propert$ Implementation 8irective
Bou can ue the @s)nthesi@e an! @d)na+ic !irective in @i+p&e+entation bloc+ to trigger
peci#ic
compiler action. "ote that neither i re-uired #or an$ given @propert) !eclaration.
,"portant: I# $ou !o not peci#$ either @s)nthesi@e or @d)na+ic #or a particular propert$% $ou mut
provi!e a getter an! etter Eor jut a getter in the cae o# a readon&) propert$F metho! implementation #or
that propert$. I# $ou !o not% the compiler generate a &arning.
@s)nthesi@e
Bou ue the @s)nthesi@e !irective to tell the compiler that it houl! $nthei)e the etter an!6or
getter metho! #or a propert$ i# $ou !o not uppl$ them &ithin the @i+p&e+entation bloc+.
Listing A-2 4ing D$nthei)e
@interface 4)C&ass : NS#$%ect
{
NSString *va&ue
"
@propert)(cop)3 read8rite) NSString *va&ue
@end
@i+p&e+entation 4)C&ass
@s)nthesi@e va&ue
@end
Bou can ue the #orm propert)5ivar to in!icate that a particular intance variable houl! be ue!
#or the propert$% #or e'ample(
@s)nthesi@e firstNa+e3 &astNa+e3 age 5 )ears#&d
Thi peci#ie that the acceor metho! #or firstNa+e% &astNa+e% an! age houl! be $nthei)e!
an! that the propert$ age i repreente! b$ the intance variable )ears#&d. Other apect o# the
$nthei)e! metho! are !etermine! b$ the optional attribute Eee IPropert$ 8eclaration
AttributeJ Epage =0FF.
:hether or not $ou peci#$ the name o# the intance variable% the @s)nthesi@e !irective can ue
an intance variable onl$ #rom the current cla% not a upercla.
There are !i##erence in the behavior o# acceor $nthei that !epen! on the runtime Eee alo
I;untime 8i##erenceJ Epage /0FF(
Propert$ 8eclaration an! Implementation F@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
Aor the legac$ runtime% intance variable mut alrea!$ be !eclare! in the @interface bloc+
o# the current cla. I# an intance variable o# the ame name a the propert$ e'it% an! i# it t$pe
i compatible &ith the propert$* t$pe% it i ue!Gother&ie% $ou get a compiler error.
Aor the mo!ern runtime Eee I;untime >erion an! Plat#ormJ in Objective-C Runtime
Programming GuideF% intance variable are $nthei)e! a nee!e!. I# an intance variable o# the
ame name alrea!$ e'it% it i ue!.
@d)na+ic
Bou ue the @d)na+ic +e$&or! to tell the compiler that $ou &ill #ul#ill the API contract implie! b$ a
propert$ either b$ provi!ing metho! implementation !irectl$ or at runtime uing other mechanim
uch a !$namic loa!ing o# co!e or !$namic metho! reolution. It uppree the &arning that the
compiler &oul! other&ie generate i# it can*t #in! uitable implementation. Bou houl! ue it onl$
i# $ou +no& that the metho! &ill be available at runtime.
The e'ample ho&n in Liting --< illutrate uing @d)na+ic &ith a ubcla o# NS4anaged#$%ect.
Listing A-@ 4ing D!$namic &ith "32anage!Object
@interface 4)C&ass : NS4anaged#$%ect
{
"
@propert)(nonato+ic3 retain) NSString *va&ue
@end
@i+p&e+entation 4)C&ass
@d)na+ic va&ue
@end
NS4anaged#$%ect i provi!e! b$ the Core 8ata #rame&or+. A manage! object cla ha a
correpon!ing chema that !e#ine attribute an! relationhip #or the claL at runtime% the Core
8ata #rame&or+ generate acceor metho! #or thee a necear$. Bou there#ore t$picall$ !eclare
propertie #or the attribute an! relationhip% but $ou !on*t have to implement the acceor metho!
$ourel# an! houl!n*t a+ the compiler to !o o. I# $ou jut !eclare! the propert$ &ithout provi!ing
an$ implementation% ho&ever% the compiler &oul! generate a &arning. 4ing @d)na+ic uppree
the &arning.
4ing Propertie
3upporte! T$pe
Bou can !eclare a propert$ #or an$ Objective-C cla% Core Aoun!ation !ata t$pe% or Iplain ol! !ataJ
EPO8F
t$pe Eee CKK Language "ote( PO8 T$peF. Aor contraint on uing Core Aoun!ation t$pe% ho&ever% ee
ICore Aoun!ationJ Epage ==F.
FD 4ing Propertie
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
Propert$ ;e!eclaration
Bou can re!eclare a propert$ in a ubcla% but E&ith the e'ception o# readon&) veru read8riteF $ou
mut repeat it attribute in &hole in the ubclae. The ame hol! true #or a propert$ !eclare! in a
categor$
or protocolG&hile the propert$ ma$ be re!eclare! in a categor$ or protocol% the propert$* attribute mut
be repeate! in &hole.
I# $ou !eclare a propert$ in one cla a readon&)% $ou can re!eclare it a read8rite in a cla
e'tenion
Eee I?'tenionJ Epage /<FF% in a protocol% or in a ubcla Eee I3ubclaing &ith PropertieJ Epage =,FF.
In
the cae o# a cla e'tenion re!eclaration% the #act that the propert$ &a re!eclare! prior to an$
@s)nthesi@e
tatement caue the etter to be $nthei)e!. The abilit$ to re!eclare a rea!-onl$ propert$ a rea!6&rite
enable t&o common implementation pattern( a mutable ubcla o# an immutable cla ENSString%
NSArra)% an! NS6ictionar) are all e'ampleF an! a propert$ that ha a public API that i readon&)
but
a private read8rite implementation internal to the cla. The #ollo&ing e'ample ho& uing a cla
e'tenion to provi!e a propert$ that i !eclare! a rea!-onl$ in the public hea!er but i re!eclare! privatel$
a rea!6&rite.
(( pu$&ic header fi&e
@interface 4)#$%ect : NS#$%ect {
NSString *&anguage
"
@propert) (readon&)3 cop)) NSString *&anguage
@end
(( private i+p&e+entation fi&e
@interface 4)#$%ect ()
@propert) (read8rite3 cop)) NSString *&anguage
@end
@i+p&e+entation 4)#$%ect
@s)nthesi@e &anguage
@end
Cop$
I# $ou ue the cop) !eclaration attribute% $ou peci#$ that a value i copie! !uring aignment. I# $ou
$nthei)e
the correpon!ing acceor% the $nthei)e! metho! ue the cop) metho!. Cop$ing i ue#ul #or attribute
uch a tring object &here there i a poibilit$ that the ne& value pae! in a etter ma$ be mutable E#or
e'ample% an intance o# NS4uta$&eStringF an! $ou &ant to enure that $our object ha it o&n private
immutable cop$. Aor e'ample% i# $ou !eclare a propert$ a #ollo&(
@propert) (nonato+ic3 cop)) NSString *string
then the $nthei)e! etter metho! i imilar to the #ollo&ing(
-(void)setString:(NSString *)ne8String {
if (string G5 ne8String) {
[string re&ease]
string 5 [ne8String cop)]
"
"
4ing Propertie FA
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
Although thi pattern &or+ &ell #or tring% it ma$ preent a problem i# the attribute i a collection uch a
an arra$ or a et. T$picall$ $ou &ant uch collection to be mutable% but the cop) metho! return an
immutable
verion o# the collection. In thi ituation% $ou have to provi!e $our o&n implementation o# the etter
metho!%
a illutrate! in the #ollo&ing e'ample.
@interface 4)C&ass : NS#$%ect {
NS4uta$&eArra) *+)Arra)
"
@propert) (nonato+ic3 cop)) NS4uta$&eArra) *+)Arra)
@end
@i+p&e+entation 4)C&ass
@s)nthesi@e +)Arra)
- (void)set4)Arra):(NS4uta$&eArra) *)ne8Arra) {
if (+)Arra) G5 ne8Arra)) {
[+)Arra) re&ease]
+)Arra) 5 [ne8Arra) +uta$&eCop)]
"
"
@end
!ealloc
8eclare! propertie% along &ith the @s)nthesi@e !irective% ta+e the place o# acceor metho!
!eclarationL
&hen $ou $nthei)e a propert$% the compiler create acceor metho! a nee!e!. 7o&ever% there i no
!irect interaction bet&een propert$ !eclaration an! the dea&&oc metho!Gpropertie are not
automaticall$
releae! #or $ou. 8eclare! propertie !o% ho&ever% provi!e a ue#ul &a$ to cro-chec+ the implementation
o# $our dea&&oc metho!( $ou can loo+ #or all the propert$ !eclaration in $our hea!er #ile an! ma+e ure
that object propertie not mar+e! assign are releae!% an! thoe mar+e! assign are not releae!.
(ote: T$picall$ in a dea&&oc metho! $ou houl! releae object intance variable !irectl$ Erather than
invo+ing a et acceor an! paing ni& a the parameterF% a illutrate! in thi e'ample(
- (void)dea&&oc {
[propert) re&ease]
[super dea&&oc]
"
I# $ou are uing the mo!ern runtime an! $nthei)ing the intance variable% ho&ever% $ou cannot acce the
intance variable !irectl$% o $ou mut invo+e the acceor metho!(
- (void)dea&&oc {
[se&f set>ropert):ni&]
[super dea&&oc]
"
FE 4ing Propertie
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
Core Aoun!ation
A note! in IPropert$ 8eclaration AttributeJ Epage =0F% prior to 2ac O3 H v10.0 $ou cannot peci#$ the
retain attribute #or non-object t$pe. I#% there#ore% $ou !eclare a propert$ &hoe t$pe i a CAT$pe an!
$nthei)e the acceor a illutrate! in the #ollo&ing e'ample(
@interface 4)C&ass : NS#$%ect
{
C7?+age,ef +)?+age
"
@propert)(read8rite) C7?+age,ef +)?+age
@end
@i+p&e+entation 4)C&ass
@s)nthesi@e +)?+age
@end
then in a re#erence-counte! environment% the $nthei)e! et acceor impl$ aign the ne& value to the
intance variable Ethe ne& value i not retaine! an! the ol! value i not releae!F. 3imple aignment i
t$picall$ incorrect #or Core Aoun!ation objectL $ou houl! not $nthei)e the metho! but rather
implement
them $ourel#.
In a garbage collecte! environment% i# the image variable i !eclare! **strong(
!!!
**strong C7?+age,ef +)?+age
!!!
@propert) C7?+age,ef +)?+age
then the acceor are $nthei)e! appropriatel$Gthe image in thi e'ample i not retaine! b$ C9,etain%
but the $nthei)e! etter metho! trigger a &rite barrier.
?'ample( 8eclaring Propertie an! 3$nthei)ing Acceor
The e'ample in Liting --. illutrate the ue o# propertie in everal !i##erent &a$(
The =ink protocol !eclare a propert$% ne2t.
4)C&ass a!opt the =ink protocol% o it implicitl$ alo !eclare the propert$ ne2t. 4)C&ass alo
!eclare
everal other propertie.
creation1i+esta+p an! ne2t are $nthei)e! but ue e'iting intance variable &ith !i##erent
name.
na+e i $nthei)e! an! ue intance variable $nthei Erecall that intance variable $nthei i not
upporte! uing the legac$ runtimeGee IPropert$ Implementation 8irectiveJ Epage =<F an! I;untime
8i##erenceJ Epage /0FF.
gratuitous9&oat ha a d)na+ic !irectiveGit i upporte! uing !irect metho! implementation.
na+eAndAge !oe not have a d)na+ic !irective% but thi i the !e#ault valueL it i upporte! uing a
!irect metho! implementation Eince it i rea!-onl$% it re@uire onl$ a getterF &ith a peci#ie! name
Ena+eAndAgeAsStringF.
4ing Propertie FF
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
Listing A-D 8eclaring propertie #or a cla
@protoco& =ink
@propert) id N=inkO ne2t
@end
@interface 4)C&ass : NS#$%ect N=inkO
{
NS1i+e?nterva& interva&Since,eference6ate
C79&oat gratuitous9&oat
id N=inkO ne2t=ink
"
@propert)(readon&)) NS1i+e?nterva& creation1i+esta+p
@propert)(cop)) NSString *na+e
@propert) C79&oat gratuitous9&oat
@propert)(readon&)3 getter5na+eAndAgeAsString) NSString *na+eAndAge
@end
@i+p&e+entation 4)C&ass
@s)nthesi@e creation1i+esta+p 5 interva&Since,eference6ate3 na+e
(( S)nthesi@ing Jna+eJ is an error in &egac) runti+es
(( in +odern runti+es3 the instance varia$&e is s)nthesi@ed!
@s)nthesi@e ne2t 5 ne2t=ink
(( Qses instance varia$&e Cne2t=inkC for storage!
@d)na+ic gratuitous9&oat
(( 1his directive is not strict&) necessar)!
- (C79&oat)gratuitous9&oat {
return gratuitous9&oat
"
- (void)set7ratuitous9&oat:(C79&oat)aEa&ue {
gratuitous9&oat 5 aEa&ue
"
- (NSString *)na+eAndAgeAsString {
return [NSString stringWith9or+at:@CD@ (Dfs)C3 [se&f na+e]3
[NS6ate ti+e?nterva&Since,eference6ate] -
interva&Since,eference6ate]
"
- (id)init {
se&f 5 [super init]
if (se&f) {
interva&Since,eference6ate 5 [NS6ate ti+e?nterva&Since,eference6ate]
"
return se&f
"
- (void)dea&&oc {
[ne2t=ink re&ease]
F8 4ing Propertie
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
[na+e re&ease]
[super dea&&oc]
"
@end
3ubclaing &ith Propertie
Bou can overri!e a readon&) propert$ to ma+e it &ritable. Aor e'ample% $ou coul! !e#ine a cla
4)?nteger
&ith a readon&) propert$% va&ue(
@interface 4)?nteger : NS#$%ect
{
NS?nteger va&ue
"
@propert)(readon&)) NS?nteger va&ue
@end
@i+p&e+entation 4)?nteger
@s)nthesi@e va&ue
@end
Bou coul! then implement a ubcla% 4)4uta$&e?nteger% &hich re!e#ine the propert$ to ma+e it
&ritable(
@interface 4)4uta$&e?nteger : 4)?nteger
@propert)(read8rite) NS?nteger va&ue
@end
@i+p&e+entation 4)4uta$&e?nteger
@d)na+ic va&ue
- (void)setEa&ue:(NS?nteger)ne8. {
va&ue 5 ne8.
"
@end
Per#ormance an! Threa!ing
I# $ou uppl$ $our o&n acceor metho! implementation% the #act that $ou !eclare! a propert$ ha no e##ect
on the metho!* e##icienc$ or threa! a#et$.
I# $ou ue a $nthei)e! acceor% the metho! implementation generate! b$ the compiler !epen! on the
peci#ication $ou uppl$ in the propert$ !eclaration. The !eclaration attribute that a##ect per#ormance an!
threa!ing are retain% assign% cop)% an! nonato+ic. The #irt three o# thee a##ect onl$ the
implementation
o# the aignment part o# the et metho!% a illutrate! belo& in a poible implementation(
(( assign
propert) 5 ne8Ea&ue
(( retain
if (propert) G5 ne8Ea&ue) {
3ubclaing &ith Propertie F?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
[propert) re&ease]
propert) 5 [ne8Ea&ue retain]
"
(( cop)
if (propert) G5 ne8Ea&ue) {
[propert) re&ease]
propert) 5 [ne8Ea&ue cop)]
"
The e##ect o# the nonato+ic attribute !epen! on the environment. 1$ !e#ault% $nthei)e! acceor are
atomic. In a re#erence-counte! environment% guaranteeing atomic behavior re@uire the ue o# a loc+L
moreover a returne! object i retaine! an! autoreleae!% a illutrate! in IAtomicit$J Epage =2F. I# uch
acceor are invo+e! #re@uentl$% guaranteeing atomicit$ ma$ have a igni#icant negative impact on
per#ormance. In a garbage-collecte! environment% mot $nthei)e! metho! are atomic &ithout incurring
thi overhea!.
It i important to un!ertan! that the goal o# the atomic implementation i to provi!e robust acceorGit
!oe not guarantee correctness o# $our co!e. Although IatomicJ mean that acce to the (ro(erty i
threa!-a#e% impl$ ma+ing all the propertie in $our cla atomic !oe not mean that $our class or more
generall$ $our object graph i Ithrea!-a#eJGthrea! a#et$ cannot be e'pree! at the level o# in!ivi!ual
acceor metho!. Aor more about multithrea!ing% ee .hreading Programming Guide.
;untime 8i##erence
In general the behavior o# propertie i i!entical on both mo!ern an! legac$ runtime Eee I;untime
>erion
an! Plat#ormJ in Objective-C Runtime Programming GuideF. There i one +e$ !i##erence( the
mo!ern runtime
upport intance variable $nthei &herea the legac$ runtime !oe not.
Aor @s)nthesi@e to &or+ in the legac$ runtime% $ou mut either provi!e an intance variable &ith the
ame
name an! compatible t$pe o# the propert$ or peci#$ another e'iting intance variable in the
@s)nthesi@e
tatement. :ith the mo!ern runtime% i# $ou !o not provi!e an intance variable% the compiler a!! one #or
$ou. Aor e'ample% given the #ollo&ing cla !eclaration an! implementation(
@interface 4)C&ass : NS#$%ect {
f&oat sa+eNa+e
f&oat otherNa+e
"
@propert) f&oat sa+eNa+e
@propert) f&oat differentNa+e
@propert) f&oat no6ec&ared?var
@end
@i+p&e+entation 4)C&ass
@s)nthesi@e sa+eNa+e
@s)nthesi@e differentNa+e5otherNa+e
@s)nthesi@e no6ec&ared?var
@end
the compiler #or the legac$ runtime &oul! generate an error at @s)nthesi@e no6ec&ared?var
&herea
the compiler #or the mo!ern runtime &oul! a!! an intance variable to repreent no6ec&ared?var.
80 ;untime 8i##erence
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* A
8eclare! Propertie
A categor: allo& $ou to a!! metho! to an e'iting claGeven to one #or &hich $ou !o not have the
ource. Categorie are a po&er#ul #eature that allo& $ou to e'ten! the #unctionalit$ o# e'iting clae
&ithout ubclaing. 4ing categorie% $ou can alo !itribute the implementation o# $our o&n clae
among
everal #ile. Cla e'tenion are imilar% but allo& a!!itional re-uired API to be !eclare! #or a cla in
location other than &ithin the primar$ cla @interface bloc+.
A!!ing 2etho! to Clae
Bou can a!! metho! to a cla b$ !eclaring them in an inter#ace #ile un!er a categor$ name an! !e#ining
them in an implementation #ile un!er the ame name. The categor$ name in!icate that the metho! are
a!!ition to a cla !eclare! ele&here% not a ne& cla. Bou cannot% ho&ever% ue a categor$ to a!!
a!!itional
intance variable to a cla.
The metho! the categor$ a!! become part o# the cla t$pe. Aor e'ample% metho! a!!e! to the NSArra)
cla in a categor$ are inclu!e! a metho! the compiler e'pect an NSArra) intance to have in it
repertoire.
2etho! a!!e! to the NSArra) cla in a ubcla% ho&ever% are not inclu!e! in the NSArra) t$pe. EThi
matter onl$ #or taticall$ t$pe! object becaue tatic t$ping i the onl$ &a$ the compiler can +no& an
object* cla.F
Categor$ metho! can !o an$thing that metho! !e#ine! in the cla proper can !o. At runtime% there* no
!i##erence. The metho! the categor$ a!! to the cla are inherite! b$ all the cla* ubclae% jut li+e
other metho!.
The !eclaration o# a categor$ inter#ace loo+ ver$ much li+e a cla inter#ace !eclarationGe'cept the
categor$
name i lite! &ithin parenthee a#ter the cla name an! the upercla in*t mentione!. 4nle it
metho!
!on*t acce an$ intance variable o# the cla% the categor$ mut import the inter#ace #ile #or the cla it
e'ten!(
Mi+port CC&assNa+e!hC
@interface C&assNa+e ( Categor)Na+e )
(( +ethod dec&arations
@end
The implementation% a uual% import it o&n inter#ace. A common naming convention i that the bae
#ilename o# the categor$ i the name o# the cla the categor$ e'ten! #ollo&e! b$ IKJ #ollo&e! b$ the
name
o# the categor$. A categor$ implementation Ein a #ile name! C&assNa+eICategor)Na+e!+F might
there#ore
loo+ li+e thi(
Mi+port CC&assNa+eICategor)Na+e!hC
@i+p&e+entation C&assNa+e ( Categor)Na+e )
(( +ethod definitions
@end
A!!ing 2etho! to Clae 81
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* E
Categorie an! ?'tenion
"ote that a categor$ can*t !eclare a!!itional intance variable #or the claL it inclu!e onl$ metho!.
7o&ever% all intance variable &ithin the cope o# the cla are alo &ithin the cope o# the categor$. That
inclu!e all intance variable !eclare! b$ the cla% even one !eclare! @private.
There* no limit to the number o# categorie that $ou can a!! to a cla% but each categor$ name mut be
!i##erent% an! each houl! !eclare an! !e#ine a !i##erent et o# metho!.
7o& Bou Can 4e Categorie
There are everal &a$ in &hich $ou can ue categorie(
To e'ten! clae !e#ine! b$ other implementor
Aor e'ample% $ou can a!! metho! to the clae !e#ine! in the Cocoa #rame&or+. The a!!e! metho!
are inherite! b$ ubclae an! are in!itinguihable at runtime #rom the original metho! o# the cla.
A an alternative to a ubcla
;ather than !e#ine a ubcla to e'ten! an e'iting cla% through a categor$ $ou can a!! metho! to
the cla !irectl$. Aor e'ample% $ou coul! a!! categorie to NSArra) an! other Cocoa clae. A in the
cae o# a ubcla% $ou !on*t nee! ource co!e #or the cla $ou*re e'ten!ing.
To !itribute the implementation o# a ne& cla into multiple ource #ile
Aor e'ample% $ou coul! group the metho! o# a large cla into everal categorie an! put each categor$
in it o&n #ile. :hen ue! li+e thi% categorie can bene#it the !evelopment proce in a number o#
&a$Gthe$(
Provi!e a imple &a$ o# grouping relate! metho!. 3imilar metho! !e#ine! in !i##erent clae can
be +ept together in the ame ource #ile.
3impli#$ the management o# a large cla &hen everal !eveloper contribute to the cla !e#inition.
Let $ou achieve ome o# the bene#it o# incremental compilation #or a ver$ large cla.
Can help improve localit$ o# re#erence #or commonl$ ue! metho!.
?nable $ou to con#igure a cla !i##erentl$ #or eparate application% &ithout having to maintain
!i##erent verion o# the ame ource co!e.
To !eclare in#ormal protocol
3ee IIn#ormal Protocol J Epage 0<F% a !icue! un!er I8eclaring Inter#ace #or Other to
ImplementJ Epage -,F.
Although the Objective-C language currentl$ allo& $ou to ue a categor$ to overri!e metho! the cla
inherit% or even metho! !eclare! in the cla inter#ace% $ou are trongl$ !icourage! #rom !oing o. A
categor$ i not a ubtitute #or a ubcla. There are everal igni#icant hortcoming to uing a categor$ to
overri!e metho!(
82 7o& Bou Can 4e Categorie
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* E
Categorie an! ?'tenion
:hen a categor$ overri!e an inherite! metho!% the metho! in the categor$ can% a uual% invo+e the
inherite! implementation via a meage to super. 7o&ever% i# a categor$ overri!e a metho! that e'it
in the categor$M cla% there i no &a$ to invo+e the original implementation.
A categor$ cannot reliabl$ overri!e metho! !eclare! in another categor$ o# the ame cla.
Thi iue i o# particular igni#icance becaue man$ o# the Cocoa clae are implemente! uing
categorie.
A #rame&or+-!e#ine! metho! $ou tr$ to overri!e ma$ itel# have been implemente! in a categor$% an!
o &hich implementation ta+e prece!ence i not !e#ine!.
The ver$ preence o# ome categor$ metho! ma$ caue behavior change acro all #rame&or+. Aor
e'ample% i# $ou overri!e the 8indo8Wi&&C&ose: !elegate metho! in a categor$ on NS#$%ect% all
&in!o& !elegate in $our program then repon! uing the categor$ metho!L the behavior o# all $our
intance o# NSWindo8 ma$ change. Categorie $ou a!! on a #rame&or+ cla ma$ caue m$teriou
change in behavior an! lea! to crahe.
Categorie o# the ;oot Cla
A categor$ can a!! metho! to an$ cla% inclu!ing the root cla. 2etho! a!!e! to NS#$%ect become
available to all clae that are lin+e! to $our co!e. A!!ing metho! to the root cla &ith a categor$ can be
ue#ul at time% but it can alo be @uite !angerou. Although it ma$ eem that the mo!i#ication the
categor$
ma+e are &ell un!ertoo! an! o# limite! impact% inheritance give them a &i!e cope. Bou ma$ be ma+ing
uninten!e! change to uneen clae in $our applicationL $ou ma$ not +no& all the cone@uence o# &hat
$ou*re !oing. 2oreover% other &or+ing on $our application% &ho are una&are o# $our change% &on*t
un!ertan! &hat the$*re !oing.
In a!!ition% there are t&o other coni!eration to +eep in min! &hen implementing metho! #or the root
cla(
2eage to super are invali! Ethere i no upercla o# NS#$%ectF.
Cla object can per#orm intance metho! !e#ine! in the root cla.
"ormall$% cla object can per#orm onl$ cla metho!. 1ut intance metho! !e#ine! in the root cla are
a pecial cae. The$ !e#ine an inter#ace to the runtime $tem that all object inherit. Cla object are
#ull-#le!ge! object an! nee! to hare the ame inter#ace.
Thi #eature mean that $ou nee! to ta+e into account the poibilit$ that an intance metho! $ou !e#ine in
a categor$ o# the NS#$%ect cla might be per#orme! not onl$ b$ intance but b$ cla object a &ell.
Aor
e'ample% &ithin the bo!$ o# the metho!% se&f might mean a cla object a &ell a an intance. 3ee
NSObject
Class Reference #or more in#ormation on cla acce to root intance metho!.
?'tenion
Cla e'tenion are li+e anon$mou categorie% e'cept that the metho! the$ !eclare mut be implemente!
in the main @i+p&e+entation bloc+ #or the correpon!ing cla.
Categorie o# the ;oot Cla 8@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* E
Categorie an! ?'tenion
It i common #or a cla to have a publicl$ !eclare! API an! to then have a!!itional metho! !eclare!
privatel$
#or ue olel$ b$ the cla or the #rame&or+ &ithin &hich the cla rei!e. Bou can !eclare uch metho!
in
a categor$ Eor in more than one categor$F in a private hea!er #ile or implementation #ile a mentione!
above.
Thi &or+% but the compiler cannot veri#$ that all !eclare! metho! are implemente!.
Aor e'ample% the #ollo&ing !eclaration an! implementation compile &ithout error% even though the
setNu+$er: metho! ha no implementation(
@interface 4)#$%ect : NS#$%ect
{
NSNu+$er *nu+$er
"
- (NSNu+$er *)nu+$er
@end
@interface 4)#$%ect (Setter)
- (void)setNu+$er:(NSNu+$er *)ne8Nu+$er
@end
@i+p&e+entation 4)#$%ect
- (NSNu+$er *)nu+$er {
return nu+$er
"
@end
Invo+ing setNu+$er: at runtime% ho&ever% &oul! generate an error.
Cla e'tenion allo& $ou to !eclare a!!itional re-uired metho! #or a cla in location other than
&ithin
the primar$ cla @interface bloc+% a illutrate! in the #ollo&ing e'ample(
@interface 4)#$%ect : NS#$%ect
{
NSNu+$er *nu+$er
"
- (NSNu+$er *)nu+$er
@end
@interface 4)#$%ect ()
- (void)setNu+$er:(NSNu+$er *)ne8Nu+$er
@end
@i+p&e+entation 4)#$%ect
- (NSNu+$er *)nu+$er {
return nu+$er
"
- (void)setNu+$er:(NSNu+$er *)ne8Nu+$er {
nu+$er 5 ne8Nu+$er
"
@end
"otice that in thi cae(
"o name i given in the parenthee in the econ! @interface bloc+.
8D ?'tenion
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* E
Categorie an! ?'tenion
The implementation o# the setNu+$er: metho! appear &ithin the main @i+p&e+entation bloc+
#or
the cla.
The implementation o# the setNu+$er: metho! must appear &ithin the main @i+p&e+entation bloc+
#or
the cla E$ou cannot implement it in a categor$F. I# thi i not the cae% the compiler emit a &arning that it
cannot #in! a metho! !e#inition #or setNu+$er:.
?'tenion 8A
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* E
Categorie an! ?'tenion
8E ?'tenion
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* E
Categorie an! ?'tenion
Bou ue aociative re#erence to imulate the a!!ition o# object intance variable to an e'iting cla.
Aociative re#erence are available onl$ in iO3 an! in 2ac O3 H v10.0 an! later.
A!!ing 3torage Outi!e a Cla 8e#inition
4ing aociative re#erence% $ou can a!! torage to an object &ithout mo!i#$ing the cla !eclaration. Thi
ma$ be ue#ul i# $ou !o not have acce to the ource co!e #or the cla% or i# #or binar$-compatibilit$
reaon
$ou cannot alter the la$out o# the object.
Aociation are bae! on a +e$% o #or an$ object $ou can a!! a man$ aociation a $ou &ant% each
uing
a !i##erent +e$. An aociation can alo enure that the aociate! object remain vali! #or at leat the
li#etime
o# the ource object E&ithout the poibilit$ o# intro!ucing uncollectible c$cle in a garbage-collecte!
environmentF.
Creating Aociation
Bou ue the Objective-C runtime #unction o$%c*setAssociated#$%ect to ma+e an aociation
bet&een
one object an! another. The #unction ta+e #our parameter( the ource object% a +e$% the value% an! an
aociation polic$ contant. O# thee% the +e$ an! the aociation polic$ merit #urther !icuion.
The +e$ i a void pointer. The +e$ #or each aociation mut be uni@ue. A t$pical pattern i to ue a
static variable.
The polic$ peci#ie &hether the aociate! object i aigne!% retaine!% or copie!% an! &hether the
aociation i be ma!e atomicall$ or non-atomicall$. Thi pattern i imilar to that o# the attribute o# a
!eclare! propert$ Eee IPropert$ 8eclaration AttributeJ Epage =0FF. Bou peci#$ the polic$ #or the
relationhip uing a contant Eee o$%c*Association>o&ic) an! Associative #$%ect
<ehaviorsF.
Liting =-1 ho& ho& $ou can etablih an aociation bet&een an arra$ an! a tring.
Listing F-1 ?tablihing an aociation bet&een an arra$ an! a tring
static char overvie8Le)
NSArra) *arra) 5
[[NSArra) a&&oc] initWith#$%ects:@C#neC3 @C18oC3 @C1hreeC3 ni&]
(( 9or the purposes of i&&ustration3 use initWith9or+at: to ensure
(( the string can $e dea&&ocated
NSString *overvie8 5
[[NSString a&&oc] initWith9or+at:@CD@C3 @C9irst three nu+$ersC]
A!!ing 3torage Outi!e a Cla 8e#inition 8F
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* F
Aociative ;e#erence
o$%c*setAssociated#$%ect (
arra)3
Rovervie8Le)3
overvie83
#<SC*ASS#C?A1?#N*,;1A?N
)
[overvie8 re&ease]
(( (B) overvie8 va&id
[arra) re&ease]
(( (-) overvie8 inva&id
At point 1% the tring overvie8 i till vali! becaue the #<SC*ASS#C?A1?#N*,;1A?N polic$ peci#ie
that
the arra$ retain the aociate! object. :hen the arra$ i !eallocate!% ho&ever Eat point 2F% overvie8 i
releae! an! o in thi cae alo !eallocate!. I# $ou tr$ to% #or e'ample% log the value o# overvie8% $ou
generate a runtime e'ception.
;etrieving Aociate! Object
Bou retrieve an aociate! object uing the Objective-C runtime #unction o$%c*getAssociated#$%ect.
Continuing the e'ample ho&n in Liting =-1 Epage /=F% $ou coul! retrieve the overvie& #rom the arra$
uing
the #ollo&ing line o# co!e(
NSString *associated#$%ect 5
(NSString *)o$%c*getAssociated#$%ect(arra)3 Rovervie8Le))
1rea+ing Aociation
To brea+ an aociation% $ou t$picall$ call o$%c*setAssociated#$%ect% paing ni& a the value.
Continuing the e'ample ho&n in Liting =-1 Epage /=F% $ou coul! brea+ the aociation bet&een the arra$
an! the tring overvie8 uing the #ollo&ing line o# co!e(
o$%c*setAssociated#$%ect(arra)3 Rovervie8Le)3 ni&3 #<SC*ASS#C?A1?#N*ASS?7N)
9iven that the aociate! object i being et to ni&% the polic$ in*t actuall$ important.
To brea+ all aociation #or an object% $ou can call o$%c*re+oveAssociated#$%ects. In general%
ho&ever%
$ou are !icourage! #rom uing thi #unction becaue it brea+ all aociation #or all client. 4e thi
#unction
onl$ i# $ou nee! to retore an object to Ipritine con!ition.J
Complete ?'ample
The #ollo&ing program combine co!e #rom the prece!ing ection.
Mi+port N9oundation(9oundation!hO
Mi+port No$%c(runti+e!hO
88 ;etrieving Aociate! Object
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* F
Aociative ;e#erence
int +ain (int argc3 const char * argv[]) {
NSAutore&ease>oo& * poo& 5 [[NSAutore&ease>oo& a&&oc] init]
static char overvie8Le)
NSArra) *arra) 5 [[NSArra) a&&oc]
initWith#$%ects:@ C#neC3 @C18oC3 @C1hreeC3 ni&]
(( 9or the purposes of i&&ustration3 use initWith9or+at: to ensure
(( 8e get a dea&&ocata$&e string
NSString *overvie8 5 [[NSString a&&oc]
initWith9or+at:@CD@C3 @C9irst three nu+$ersC]
o$%c*setAssociated#$%ect (
arra)3
Rovervie8Le)3
overvie83
#<SC*ASS#C?A1?#N*,;1A?N
)
[overvie8 re&ease]
NSString *associated#$%ect 5
(NSString *) o$%c*getAssociated#$%ect (arra)3 Rovervie8Le))
NS=og(@Cassociated#$%ect: D@C3 associated#$%ect)
o$%c*setAssociated#$%ect (
arra)3
Rovervie8Le)3
ni&3
#<SC*ASS#C?A1?#N*ASS?7N
)
[arra) re&ease]
[poo& drain]
return '
"
Complete ?'ample 8?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* F
Aociative ;e#erence
?0 Complete ?'ample
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* F
Aociative ;e#erence
Aat enumeration i a language #eature that allo& $ou to e##icientl$ an! a#el$ enumerate over the content
o# a collection uing a concie $nta'.
The #orCin 3$nta'
The $nta' #or #at enumeration i !e#ine! a #ollo&(
for ( Type newVariable in expression ) { statements "
or
Type existingItem
for ( existingItem in expression ) { statements "
In both cae% e/(ression $iel! an object that con#orm to the NS9ast;nu+eration protocol Eee
IA!opting
Aat ?numerationJ Epage ,1FF. The iterating variable i et to each item in the returne! object in turn% an!
the co!e !e#ine! b$ state+ents i e'ecute!. The iterating variable i et to ni& &hen the loop en! b$
e'hauting the ource pool o# object. I# the loop i terminate! earl$% the iterating variable i le#t pointing to
the lat iteration item.
There are everal a!vantage to uing #at enumeration(
The enumeration i coni!erabl$ more e##icient than% #or e'ample% uing NS;nu+erator !irectl$.
The $nta' i concie.
?numeration i Ia#eJGthe enumerator ha a mutation guar! o that i# $ou attempt to mo!i#$ the
collection !uring enumeration% an e'ception i raie!.
1ecaue mutation o# the object !uring iteration i #orbi!!en% $ou can per#orm multiple enumeration
concurrentl$.
A!opting Aat ?numeration
An$ cla &hoe intance provi!e acce to a collection o# other object can a!opt the
NS9ast;nu+eration
protocol. The collection clae in the Aoun!ation #rame&or+GNSArra)% NS6ictionar)% an! NSSetG
a!opt
thi protocol% a !oe NS;nu+erator. It houl! be obviou that in the cae o# NSArra) an! NSSet the
enumeration i over their content. Aor other clae% the correpon!ing !ocumentation houl! ma+e clear
&hat propert$ i iterate! overG#or e'ample% NS6ictionar) an! the Core 8ata cla
NS4anaged#$%ect4ode&
provi!e upport #or #at enumerationL NS6ictionar) enumerate it +e$% an! NS4anaged#$%ect4ode&
enumerate it entitie.
The #orCin 3$nta' ?1
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 8
Aat ?numeration
4ing Aat ?numeration
The #ollo&ing co!e e'ample illutrate uing #at enumeration &ith NSArra) an! NS6ictionar)
object.
NSArra) *arra) 5 [NSArra) arra)With#$%ects:
@C#neC3 @C18oC3 @C1hreeC3 @C9ourC3 ni&]
for (NSString *e&e+ent in arra)) {
NS=og(@Ce&e+ent: D@C3 e&e+ent)
"
NS6ictionar) *dictionar) 5 [NS6ictionar) dictionar)With#$%ectsAndLe)s:
@CKuattuorC3 @CfourC3 @CKuinKueC3 @CfiveC3 @Cse2C3 @Csi2C3 ni&]
NSString *ke)
for (ke) in dictionar)) {
NS=og(@C;ng&ish: D@3 =atin: D@C3 ke)3 [dictionar) o$%ect9orLe):ke)])
"
Bou can alo ue NS;nu+erator object &ith #at enumeration% a illutrate! in thi e'ample(
NSArra) *arra) 5 [NSArra) arra)With#$%ects:
@C#neC3 @C18oC3 @C1hreeC3 @C9ourC3 ni&]
NS;nu+erator *enu+erator 5 [arra) reverse#$%ect;nu+erator]
for (NSString *e&e+ent in enu+erator) {
if ([e&e+ent is;Kua&1oString:@C1hreeC]) {
$reak
"
"
NSString *ne2t 5 [enu+erator ne2t#$%ect]
(( ne2t 5 C18oC
Aor collection or enumerator that have a &ell-!e#ine! or!erGuch a an NSArra) or an NS;nu+erator
intance !erive! #rom an arra$Gthe enumeration procee! in that or!er% o impl$ counting iteration give
$ou the proper in!e' into the collection i# $ou nee! it.
NSArra) *arra) 5 (* assu+e this e2ists *(
NSQ?nteger inde2 5 '
for (id e&e+ent in arra)) {
NS=og(@C;&e+ent at inde2 Du is: D@C3 inde23 e&e+ent)
inde2II
"
In other repect% the #eature behave li+e a tan!ar! for loop. Bou can ue $reak to interrupt the
iterationL
an! i# $ou &ant to +ip element% $ou can ue a nete! con!itional tatement(
NSArra) *arra) 5 (* assu+e this e2ists *(
for (id e&e+ent in arra)) {
if ((* so+e test for e&e+ent *() {
(( state+ents that app&) on&) to e&e+ents passing test
"
"
?2 4ing Aat ?numeration
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 8
Aat ?numeration
I# $ou &ant to +ip the #irt element an! then proce no more than #ive #urther element% $ou coul! !o o
a ho&n in thi e'ample(
NSArra) *arra) 5 (* assu+e this e2ists *(
NSQ?nteger inde2 5 '
for (id e&e+ent in arra)) {
if (inde2 G5 ') {
NS=og(@C;&e+ent at inde2 Du is: D@C3 inde23 e&e+ent)
"
if (IIinde2 O5 T) {
$reak
"
"
4ing Aat ?numeration ?@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 8
Aat ?numeration
?D 4ing Aat ?numeration
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 8
Aat ?numeration
Thi chapter e'plain ho& tatic t$ping &or+ an! !icue ome other #eature o# Objective-C% inclu!ing
&a$ to temporaril$ overcome it inherent !$namim.
8e#ault 8$namic 1ehavior
1$ !eign% Objective-C object are !$namic entitie. A man$ !eciion about them a poible are puhe!
#rom compile time to runtime(
The memor$ #or object i !:na"icall: allocate! at runtime b$ cla metho! that create ne&
intance.
Object are !:na"icall: t:pe!. In ource co!e Eat compile timeF% an$ object variable can be o# t$pe id
no matter &hat the object* cla i. The e'act cla o# an id variable Ean! there#ore it particular metho!
an! !ata tructureF in*t !etermine! until the program run.
2eage an! metho! are !:na"icall: boun!% a !ecribe! in I8$namic 1in!ingJ Epage 1,F. A
runtime
proce!ure matche the metho! elector in the meage to a metho! implementation that Ibelong toJ
the receiver.
Thee #eature give object-oriente! program a great !eal o# #le'ibilit$ an! po&er% but there* a price to
pa$.
In particular% the compiler can*t chec+ the e'act t$pe EclaeF o# id variable. To permit better compile-
time
t$pe chec+ing% an! to ma+e co!e more el#-!ocumenting% Objective-C allo& object to be taticall$ t$pe!
&ith a cla name rather than genericall$ t$pe! a id. Objective-C alo let $ou turn o## ome o# it
object-oriente! #eature in or!er to hi#t operation #rom runtime bac+ to compile time.
(ote: 2eage are ome&hat lo&er than #unction call% t$picall$ incurring an inigni#icant amount o#
overhea! compare! to actual &or+ per#orme!. The e'ceptionall$ rare cae &here b$paing the !$namim
o# Objective-C might be &arrante! can be proven b$ ue o# anal$i tool li+e 3har+ or Intrument.
3tatic T$ping
I# a pointer to a cla name i ue! in place o# id in an object !eclaration uch a
,ectang&e *this#$%ect
the compiler retrict the value o# the !eclare! variable to be either an intance o# the cla name! in the
!eclaration or an intance o# a cla that inherit #rom the name! cla. In the e'ample above% this#$%ect
can be onl$ a ,ectang&e object o# ome +in!.
8e#ault 8$namic 1ehavior ?A
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* ?
?nabling 3tatic 1ehavior
3taticall$ t$pe! object have the ame internal !ata tructure a object !eclare! to be o# t$pe id. The t$pe
!oen*t a##ect the objectL it a##ect onl$ the amount o# in#ormation given to the compiler about the object
an! the amount o# in#ormation available to thoe rea!ing the ource co!e.
3tatic t$ping alo !oen*t a##ect ho& the object i treate! at runtime. 3taticall$ t$pe! object are
!$namicall$
allocate! b$ the ame cla metho! that create intance o# t$pe id. I# SKuare i a ubcla o#
,ectang&e%
the #ollo&ing co!e &oul! till pro!uce an object &ith all the intance variable o# a SKuare object% not
jut
thoe o# a ,ectang&e object(
,ectang&e *this#$%ect 5 [[SKuare a&&oc] init]
2eage ent to taticall$ t$pe! object are !$namicall$ boun!% jut a meage to object t$pe! id are.
The e'act t$pe o# a taticall$ t$pe! receiver i till !etermine! at runtime a part o# the meaging proce.
A disp&a) meage ent to the this#$%ect object(
[this#$%ect disp&a)]
per#orm the verion o# the metho! !e#ine! in the SKuare cla% not the one in it ,ectang&e upercla.
1$ giving the compiler more in#ormation about an object% tatic t$ping open up poibilitie that are abent
#or object t$pe! id(
In certain ituation% it allo& #or compile-time t$pe chec+ing.
It can #ree object #rom the retriction that i!enticall$ name! metho! mut have i!entical return an!
parameter t$pe.
It permit $ou to ue the tructure pointer operator to !irectl$ acce an object* intance variable.
The #irt t&o poibilitie are !icue! in the ection that #ollo&. The thir! i covere! in I8e#ining a
ClaJ Epage <-F.
T$pe Chec+ing
:ith the a!!itional in#ormation provi!e! b$ tatic t$ping% the compiler can !eliver better t$pe-chec+ing
ervice in t&o ituation(
:hen a meage i ent to a taticall$ t$pe! receiver% the compiler can ma+e ure the receiver can
repon!. A &arning i iue! i# the receiver !oen*t have acce to the metho! name! in the meage.
:hen a taticall$ t$pe! object i aigne! to a taticall$ t$pe! variable% the compiler ma+e ure the
t$pe are compatible. A &arning i iue! i# the$*re not.
An aignment can be ma!e &ithout &arning% provi!e! the cla o# the object being aigne! i i!entical
to% or inherit #rom% the cla o# the variable receiving the aignment. The #ollo&ing e'ample illutrate
thi(
Shape *aShape
,ectang&e *a,ect
a,ect 5 [[,ectang&e a&&oc] init]
aShape 5 a,ect
?E T$pe Chec+ing
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* ?
?nabling 3tatic 1ehavior
7ere a,ect can be aigne! to aShape becaue a rectangle i a +in! o# hapeGthe ,ectang&e cla
inherit
#rom Shape. 7o&ever% i# the role o# the t&o variable are revere! an! aShape i aigne! to a,ect% the
compiler generate a &arningL not ever$ hape i a rectangle. EAor re#erence% ee Aigure 1-2 Epage 2-F%
&hich
ho& the cla hierarch$ inclu!ing Shape an! ,ectang&e.F
There* no chec+ &hen the e'preion on either i!e o# the aignment operator i o# t$pe id. A taticall$
t$pe! object can be #reel$ aigne! to an id object% or an id object to a taticall$ t$pe! object. 1ecaue
metho! li+e a&&oc an! init return object o# t$pe id% the compiler !oen*t enure that a compatible
object
i returne! to a taticall$ t$pe! variable. The #ollo&ing co!e i error-prone% but i allo&e! nonethele(
,ectang&e *a,ect
a,ect 5 [[Shape a&&oc] init]
;eturn an! Parameter T$pe
In general% metho! in !i##erent clae that have the ame elector Ethe ame nameF mut alo hare the
ame return an! parameter t$pe. Thi contraint i impoe! b$ the compiler to allo& !$namic bin!ing.
1ecaue the cla o# a meage receiver Ean! there#ore cla-peci#ic !etail about the metho! it* a+e! to
per#ormF% can*t be +no&n at compile time% the compiler mut treat all metho! &ith the ame name ali+e.
:hen it prepare in#ormation on metho! return an! parameter t$pe #or the runtime $tem% it create jut
one metho! !ecription #or each metho! elector.
7o&ever% &hen a meage i ent to a taticall$ t$pe! object% the cla o# the receiver i +no&n b$ the
compiler. The compiler ha acce to cla-peci#ic in#ormation about the metho!. There#ore% the meage
i #ree! #rom the retriction on it return an! parameter t$pe.
3tatic T$ping to an Inherite! Cla
An intance can be taticall$ t$pe! to it o&n cla or to an$ cla that it inherit #rom. All intance% #or
e'ample% can be taticall$ t$pe! a NS#$%ect.
7o&ever% the compiler un!ertan! the cla o# a taticall$ t$pe! object onl$ #rom the cla name in the
t$pe
!eignation% an! it !oe it t$pe chec+ing accor!ingl$. T$ping an intance to an inherite! cla can
there#ore
reult in !icrepancie bet&een &hat the compiler thin+ &oul! happen at runtime an! &hat actuall$
happen.
Aor e'ample% i# $ou taticall$ t$pe a ,ectang&e intance a Shape a ho&n here(
Shape *+),ectang&e 5 [[,ectang&e a&&oc] init]
the compiler treat it a a Shape intance. I# $ou en! the object a meage to per#orm a ,ectang&e
metho!%
<##= so&id 5 [+),ectang&e is9i&&ed]
the compiler complain. The is9i&&ed metho! i !e#ine! in the ,ectang&e cla% not in Shape.
7o&ever% i# $ou en! it a meage to per#orm a metho! that the Shape cla +no& about uch a
[+),ectang&e disp&a)]
;eturn an! Parameter T$pe ?F
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* ?
?nabling 3tatic 1ehavior
the compiler !oen*t complain% even though ,ectang&e overri!e the metho!. At runtime% the
,ectang&e
verion o# the metho! i per#orme!.
3imilarl$% uppoe that the Qpper cla !eclare a 8orr) metho! that return a dou$&e a ho&n here(
- (dou$&e)8orr)
an! the 4idd&e ubcla o# Qpper overri!e the metho! an! !eclare a ne& return t$pe(
- (int)8orr)
I# an intance i taticall$ t$pe! to the Qpper cla% the compiler thin+ that it 8orr) metho! return a
dou$&e% an! i# an intance i t$pe! to the 4idd&e cla% the compiler thin+ that 8orr) return an int.
?rror
reult i# a 4idd&e intance i t$pe! to the Qpper cla( The compiler in#orm the runtime $tem that a
8orr)
meage ent to the object return a dou$&e% but at runtime it actuall$ return an int an! generate an
error.
3tatic t$ping can #ree i!enticall$ name! metho! #rom the retriction that the$ mut have i!entical return
an! parameter t$pe% but it can !o o reliabl$ onl$ i# the metho! are !eclare! in !i##erent branche o# the
cla hierarch$.
?8 3tatic T$ping to an Inherite! Cla
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* ?
?nabling 3tatic 1ehavior
In Objective-C% selector ha t&o meaning. It can be ue! to re#er impl$ to the name o# a metho! &hen
it*
ue! in a ource-co!e meage to an object. It alo% though% re#er to the uni@ue i!enti#ier that replace the
name &hen the ource co!e i compile!. Compile! elector are o# t$pe S;=. All metho! &ith the ame
name have the ame elector. Bou can ue a elector to invo+e a metho! on an objectGthi provi!e the
bai #or the implementation o# the target-action !eign pattern in Cocoa.
2etho! an! 3elector
Aor e##icienc$% #ull A3CII name are not ue! a metho! elector in compile! co!e. Intea!% the compiler
&rite each metho! name into a table% then pair the name &ith a uni@ue i!enti#ier that repreent the
metho! at runtime. The runtime $tem ma+e ure each i!enti#ier i uni@ue( "o t&o elector are the ame%
an! all metho! &ith the ame name have the ame elector.
3?L an! Delector
Compile! elector are aigne! to a pecial t$pe% S;=% to !itinguih them #rom other !ata. >ali! elector
are never '. Bou mut let the $tem aign S;= i!enti#ier to metho!L it* #utile to aign them
arbitraril$.
The @se&ector() !irective let $ou re#er to the compile! elector% rather than to the #ull metho! name.
7ere% the elector #or setWidth:height: i aigne! to the setWidthFeight variable(
S;= setWidthFeight
setWidthFeight 5 @se&ector(setWidth:height:)
It* mot e##icient to aign value to S;= variable at compile time &ith the @se&ector() !irective.
7o&ever%
in ome cae% $ou ma$ nee! to convert a character tring to a elector at runtime. Bou can !o thi &ith the
NSSe&ector9ro+String #unction(
setWidthFeight 5 NSSe&ector9ro+String(a<uffer)
Converion in the oppoite !irection i alo poible. The NSString9ro+Se&ector #unction return a
metho!
name #or a elector(
NSString *+ethod
+ethod 5 NSString9ro+Se&ector(setWidthFeight)
2etho! an! 3elector ??
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 10
3elector
2etho! an! 3elector
Compile! elector i!enti#$ metho! name% not metho! implementation. The disp&a) metho! #or one
cla% #or e'ample% ha the ame elector a disp&a) metho! !e#ine! in other clae. Thi i eential #or
pol$morphim an! !$namic bin!ingL it let $ou en! the ame meage to receiver belonging to !i##erent
clae. I# there &ere one elector per metho! implementation% a meage &oul! be no !i##erent #rom a
#unction call.
A cla metho! an! an intance metho! &ith the ame name are aigne! the ame elector. 7o&ever%
becaue o# their eparate !omain% there* no con#uion bet&een the t&o. A cla coul! !e#ine a disp&a)
cla metho! in a!!ition to a disp&a) intance metho!.
2etho! ;eturn an! Parameter T$pe
The meaging routine ha acce to metho! implementation onl$ through elector% o it treat all
metho!
&ith the ame elector ali+e. It !icover the return t$pe o# a metho!% an! the !ata t$pe o# it parameter%
#rom the elector. There#ore% e'cept #or meage ent to taticall$ t$pe! receiver% !$namic bin!ing
re@uire
all implementation o# i!enticall$ name! metho! to have the ame return t$pe an! the ame parameter
t$pe. E3taticall$ t$pe! receiver are an e'ception to thi rule becaue the compiler can learn about the
metho! implementation #rom the cla t$pe.F
Although i!enticall$ name! cla metho! an! intance metho! are repreente! b$ the ame elector% the$
can have !i##erent parameter t$pe an! return t$pe.
>ar$ing the 2eage at ;untime
The perfor+Se&ector:% perfor+Se&ector:8ith#$%ect:% an!
perfor+Se&ector:8ith#$%ect:8ith#$%ect: metho!% !e#ine! in the NS#$%ect protocol% ta+e S;=
i!enti#ier a their initial parameter. All three metho! map !irectl$ into the meaging #unction. Aor
e'ample%
[friend perfor+Se&ector:@se&ector(gossipA$out:)
8ith#$%ect:aNeigh$or]
i e@uivalent to(
[friend gossipA$out:aNeigh$or]
Thee metho! ma+e it poible to var$ a meage at runtime% jut a it* poible to var$ the object that
receive the meage. >ariable name can be ue! in both halve o# a meage e'preion(
id he&per 5 get1he,eceiver()
S;= reKuest 5 get1heSe&ector()
[he&per perfor+Se&ector:reKuest]
In thi e'ample% the receiver Ehe&perF i choen at runtime Eb$ the #ictitiou get1he,eceiver #unctionF%
an! the metho! the receiver i a+e! to per#orm EreKuestF i alo !etermine! at runtime Eb$ the e@uall$
#ictitiou get1heSe&ector #unctionF.
100 >ar$ing the 2eage at ;untime
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 10
3elector
(ote: perfor+Se&ector: an! it companion metho! return an object o# t$pe id. I# the metho! that*
per#orme! return a !i##erent t$pe% it houl! be cat to the proper t$pe. E7o&ever% cating !oen*t &or+ #or
all t$peL the metho! houl! return a pointer or a t$pe compatible &ith a pointer.F
The Target-Action 8eign Pattern
In it treatment o# uer-inter#ace control% AppNit ma+e goo! ue o# the abilit$ to var$ both the receiver
an!
the meage at runtime.
NSContro& object are graphical !evice that can be ue! to give intruction to an application. 2ot
reemble real-&orl! control !evice uch a button% &itche% +nob% te't #iel!% !ial% menu item% an! the
li+e. In o#t&are% thee !evice tan! bet&een the application an! the uer. The$ interpret event coming
#rom har!&are !evice uch a the +e$boar! an! moue an! tranlate them into application-peci#ic
intruction. Aor e'ample% a button labele! IAin!J &oul! tranlate a moue clic+ into an intruction #or the
application to tart earching #or omething.
AppNit !e#ine a template #or creating control !evice an! !e#ine a #e& o##-the-hel# !evice o# it o&n.
Aor
e'ample% the NS<uttonCe&& cla !e#ine an object that $ou can aign to an NS4atri2 intance an!
initiali)e &ith a i)e% a label% a picture% a #ont% an! a +e$boar! hortcut. :hen the uer clic+ the button Eor
ue the +e$boar! hortcutF% the NS<uttonCe&& object en! a meage intructing the application to !o
omething. To !o thi% an NS<uttonCe&& object mut be initiali)e! not jut &ith an image% a i)e% an! a
label% but &ith !irection on &hat meage to en! an! &ho to en! it to. Accor!ingl$% an NS<uttonCe&&
intance can be initiali)e! #or an action meage Ethe metho! elector it houl! ue in the meage it en!F
an! a target Ethe object that houl! receive the meageF.
[+)<uttonCe&& setAction:@se&ector(reap1heWind:)]
[+)<uttonCe&& set1arget:an#$%ect]
:hen the uer clic+ the correpon!ing button% the button cell en! the meage uing the NS#$%ect
protocol metho! perfor+Se&ector:8ith#$%ect:. All action meage ta+e a ingle parameter% the id
o# the control !evice en!ing the meage.
I# Objective-C !i!n*t allo& the meage to be varie!% all NS<uttonCe&& object &oul! have to en! the
ame
meageL the name o# the metho! &oul! be #ro)en in the NS<uttonCe&& ource co!e. Intea! o# impl$
implementing a mechanim #or tranlating uer action into action meage% button cell an! other control
&oul! have to contrain the content o# the meage. Contraine! meaging &oul! ma+e it !i##icult #or an$
object to repon! to more than one button cell. There &oul! either have to be one target #or each button%
or the target object &oul! have to !icover &hich button the meage came #rom an! act accor!ingl$. ?ach
time $ou rearrange! the uer inter#ace% $ou &oul! alo have to reimplement the metho! that repon! to
the action meage. An abence o# !$namic meaging &oul! create an unnecear$ complication that
Objective-C happil$ avoi!.
Avoi!ing 2eaging ?rror
I# an object receive a meage to per#orm a metho! that in*t in it repertoire% an error reult. It* the ame
ort o# error a calling a none'itent #unction. 1ut becaue meaging occur at runtime% the error o#ten
in*t
evi!ent until the program e'ecute.
The Target-Action 8eign Pattern 101
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 10
3elector
It* relativel$ ea$ to avoi! thi error &hen the meage elector i contant an! the cla o# the receiving
object i +no&n. A $ou &rite $our program% $ou can ma+e ure that the receiver i able to repon!. I# the
receiver i taticall$ t$pe!% the compiler per#orm thi tet #or $ou.
7o&ever% i# the meage elector or the cla o# the receiver varie% it ma$ be necear$ to potpone thi
tet
until runtime. The responds1oSe&ector: metho!% !e#ine! in the NS#$%ect cla% tet &hether a
receiver
can repon! to a meage. It ta+e the metho! elector a a parameter an! return &hether the receiver ha
acce to a metho! matching the elector(
if ( [an#$%ect responds1oSe&ector:@se&ector(set#rigin::)] )
[an#$%ect set#rigin:'!' :'!']
e&se
fprintf(stderr3 CDs canUt $e p&acedVnC3
[NSString9ro+C&ass([an#$%ect c&ass]) Q19WString])
The responds1oSe&ector: runtime tet i epeciall$ important &hen $ou en! meage to object that
$ou !on*t have control over at compile time. Aor e'ample% i# $ou &rite co!e that en! a meage to an
object
repreente! b$ a variable that other can et% $ou houl! ma+e ure the receiver implement a metho! that
can repon! to the meage.
(ote: An object can alo arrange to have meage it receive #or&ar!e! to other object i# it !oen*t
repon!
to them !irectl$ itel#. In that cae% #rom the caller* perpective% the object appear to han!le the meage
!irectl$% even though it han!le the meage in!irectl$ b$ #or&ar!ing it to another object. 3ee I2eage
Aor&ar!ingJ in Objective-C Runtime Programming Guide #or more in#ormation.
102 Avoi!ing 2eaging ?rror
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 10
3elector
The Objective-C language ha an e'ception-han!ling $nta' imilar to that o# 5ava an! CKK. 1$ uing thi
$nta' &ith the NS;2ception% NS;rror% or cutom clae% $ou can a!! robut error-han!ling to $our
program. Thi chapter provi!e a ummar$ o# e'ception $nta' an! han!lingL #or more !etail% ee
)/ce(tion
Programming .o(ics.
?nabling ?'ception-7an!ling
4ing 9"4 Compiler Collection E9CCF verion <.< an! later% Objective-C provi!e language-level upport
#or
e'ception han!ling. To turn on upport #or thee #eature% ue the -fo$%c-e2ceptions &itch o# the
9"4
Compiler Collection E9CCF verion <.< an! later. E"ote that thi &itch ren!er the application runnable
onl$
in 2ac O3 H v10.< an! later becaue runtime upport #or e'ception han!ling an! $nchroni)ation i not
preent in earlier verion o# the o#t&are.F
?'ception 7an!ling
An e'ception i a pecial con!ition that interrupt the normal #lo& o# program e'ecution. There are a
variet$
o# reaon &h$ an e'ception ma$ be generate! Ee'ception are t$picall$ ai! to be raised or thrownF% b$
har!&are a &ell a o#t&are. ?'ample inclu!e arithmetical error uch a !iviion b$ )ero% un!er#lo& or
over#lo&% calling un!e#ine! intruction Euch a attempting to invo+e an unimplemente! metho!F% an!
attempting to acce a collection element out o# boun!.
Objective-C e'ception upport involve #our compiler !irective( @tr)% @catch% @thro8% an! @fina&&)(
Co!e that can potentiall$ thro& an e'ception i encloe! in a @tr){" bloc+.
A @catch{" bloc+ contain e'ception-han!ling logic #or e'ception thro&n in a @tr){" bloc+. Bou
can
have multiple @catch{" bloc+ to catch !i##erent t$pe o# e'ception. EAor a co!e e'ample% ee ICatching
8i##erent T$pe o# ?'ceptionJ Epage 10.F.F
Bou ue the @thro8 !irective to thro& an e'ception% &hich i eentiall$ an Objective-C object. Bou
t$picall$ ue an NS;2ception object% but $ou are not re@uire! to.
A @fina&&){" bloc+ contain co!e that mut be e'ecute! &hether an e'ception i thro&n or not.
Thi e'ample !epict a imple e'ception-han!ling algorithm(
Cup *cup 5 [[Cup a&&oc] init]
@tr) {
[cup fi&&]
"
?nabling ?'ception-7an!ling 10@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 11
?'ception 7an!ling
@catch (NS;2ception *e2ception) {
NS=og(@C+ain: Caught D@: D@C3 [e2ception na+e]3 [e2ception reason])
"
@fina&&) {
[cup re&ease]
"
Catching 8i##erent T$pe o# ?'ception
To catch an e'ception thro&n in a @tr){" bloc+% ue one or more @catch{"bloc+ #ollo&ing the @tr){"
bloc+. The @catch{" bloc+ houl! be or!ere! #rom mot-peci#ic to leat-peci#ic. That &a$ $ou can
tailor
the proceing o# e'ception a group% a ho&n in Liting 11-1.
Listing 11-1 An e'ception han!ler
@tr) {
!!!
"
@catch (Custo+;2ception *ce) { (( B
!!!
"
@catch (NS;2ception *ne) { (( -
(( >erfor+ processing necessar) at this &eve&!
!!!
"
@catch (id ue) {
!!!
"
@fina&&) { (( /
(( >erfor+ processing necessar) 8hether an e2ception occurred or not!
!!!
"
The #ollo&ing lit !ecribe the numbere! co!e line(
14 Catche the mot peci#ic e'ception t$pe.
24 Catche a more general e'ception t$pe.
@4 Per#orm an$ clean-up proceing that mut al&a$ be per#orme!% &hether e'ception &ere thro&n or
not.
Thro&ing ?'ception
To thro& an e'ception% $ou mut intantiate an object &ith the appropriate in#ormation% uch a the
e'ception
name an! the reaon it &a thro&n.
NS;2ception *e2ception 5 [NS;2ception e2ceptionWithNa+e: @CFot1ea;2ceptionC
reason: @C1he tea is too hotC
10D Catching 8i##erent T$pe o# ?'ception
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 11
?'ception 7an!ling
user?nfo: ni&]
@thro8 e2ception
,"portant: In man$ environment% ue o# e'ception i #airl$ commonplace. Aor e'ample% $ou might
thro&
an e'ception to ignal that a routine coul! not e'ecute normall$Guch a &hen a #ile i miing or !ata
coul! not be pare! correctl$. ?'ception are reource-intenive in Objective-C. Bou houl! not ue
e'ception
#or general #lo&-control% or impl$ to igni#$ error. Intea! $ou houl! ue the return value o# a metho! or
#unction to in!icate that an error ha occurre!% an! provi!e in#ormation about the problem in an error
object.
Aor more in#ormation% ee )rror *andling Programming Guide.
Ini!e a @catch{" bloc+% $ou can rethro& the caught e'ception uing the @thro8 !irective &ithout
provi!ing
an argument. Leaving out the argument in thi cae can help ma+e $our co!e more rea!able.
Bou are not limite! to thro&ing NS;2ception object. Bou can thro& an$ Objective-C object a an
e'ception
object. The NS;2ception cla provi!e metho! that help in e'ception proceing% but $ou can
implement
$our o&n i# $ou o !eire. Bou can alo ubcla NS;2ception to implement peciali)e! t$pe o#
e'ception%
uch a #ile-$tem e'ception or communication e'ception.
Thro&ing ?'ception 10A
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 11
?'ception 7an!ling
10E Thro&ing ?'ception
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 11
?'ception 7an!ling
Objective-C provi!e upport #or threa! $nchroni)ation an! e'ception han!ling% &hich are e'plaine! in
thi
chapter an! in I?'ception 7an!lingJ Epage 10<F. To turn on upport #or thee #eature% ue the
-fo$%c-e2ceptions &itch o# the 9"4 Compiler Collection E9CCF verion <.< an! later.
(ote: 4ing either o# thee #eature in a program ren!er the application runnable onl$ in 2ac O3 H v10.<
an! later becaue runtime upport #or e'ception han!ling an! $nchroni)ation i not preent in earlier
verion o# the o#t&are.
Objective-C upport multithrea!ing in application. There#ore% t&o threa! can tr$ to mo!i#$ the ame
object
at the ame time% a ituation that can caue eriou problem in a program. To protect ection o# co!e #rom
being e'ecute! b$ more than one threa! at a time% Objective-C provi!e the @s)nchroni@ed() !irective.
The @s)nchroni@ed()!irective loc+ a ection o# co!e #or ue b$ a ingle threa!. Other threa! are
bloc+e!
until the threa! e'it the protecte! co!eGthat i% &hen e'ecution continue pat the lat tatement in the
@s)nchroni@ed() bloc+.
The @s)nchroni@ed() !irective ta+e a it onl$ argument an$ Objective-C object% inclu!ing se&f. Thi
object i +no&n a a mutual e/clusion sema(hore or "ute=. It allo& a threa! to loc+ a ection o#
co!e to
prevent it ue b$ other threa!. Bou houl! ue eparate emaphore to protect !i##erent critical ection
o# a program. It* a#et to create all the mutual e'cluion object be#ore the application become
multithrea!e!% to avoi! race con!ition.
Liting 12-1 ho& co!e that ue se&f a the mute' to $nchroni)e acce to the intance metho! o# the
current object. Bou can ta+e a imilar approach to $nchroni)e the cla metho! o# the aociate! cla%
uing the cla object intea! o# se&f. In the latter cae% o# coure% onl$ one threa! at a time i allo&e! to
e'ecute a cla metho! becaue there i onl$ one cla object that i hare! b$ all caller.
Listing 12-1 Loc+ing a metho! uing el#
- (void)critica&4ethod
{
@s)nchroni@ed(se&f) {
(( Critica& code!
!!!
"
"
Liting 12-2 ho& a general approach. 1e#ore e'ecuting a critical proce% the co!e obtain a emaphore
#rom the Account cla an! ue it to loc+ the critical ection. The Account cla coul! create the
emaphore
in it initia&i@e metho!.
Listing 12-2 Loc+ing a metho! uing a cutom emaphore
Account *account 5 [Account account9ro+String:[account9ie&d stringEa&ue]]
(( 7et the se+aphore!
10F
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 12
Threa!ing
id accountSe+aphore 5 [Account se+aphore]
@s)nchroni@ed(accountSe+aphore) {
(( Critica& code!
!!!
"
The Objective-C $nchroni)ation #eature upport recurive an! reentrant co!e. A threa! can ue a ingle
emaphore everal time in a recurive mannerL other threa! are bloc+e! #rom uing it until the threa!
releae all the loc+ obtaine! &ith itL that i% ever$ @s)nchroni@ed() bloc+ i e'ite! normall$ or
through
an e'ception.
:hen co!e in an @s)nchroni@ed() bloc+ thro& an e'ception% the Objective-C runtime catche the
e'ception% releae the emaphore Eo that the protecte! co!e can be e'ecute! b$ other threa!F% an!
rethro& the e'ception to the ne't e'ception han!ler.
108
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
C-A$TE* 12
Threa!ing
Thi table !ecribe the change to .he Objective-C Programming 0anguage.
/ate (otes
2010-12-0/ ?!ite! #or content an! clarit$.
2010-0=-1< 4p!ate! to ho& the revie! initiali)ation pattern.
200,-10-1, A!!e! !icuion o# aociative re#erence.
200,-0/-12 Correcte! minor error.
200,-0--00 4p!ate! article on 2i'ing Objective-C an! CKK.
200,-02-0. 4p!ate! !ecription o# categorie.
200/-11-1, 3igni#icant reorgani)ation%&ith everal ectionmove! to a ne&;untime 9ui!e.
200/-10-1- Correcte! t$pographical error.
200/-0=-0/ Correcte! t$pographical error.
2a!e everal minor bug #i'e an! clari#ication% particularl$ in the QPropertieQ
chapter.
200/-00-0,
200/-02-0/ ?'ten!e! the !icuion o# propertie to inclu!e mutable object.
200=-12-11 Correcte! minor error.
Provi!e! an e'ample o# #at enumeration #or !ictionarie an! enhance! the
!ecription o# propertie.
200=-10-<1
200=-0=-22 A!!e! re#erence to !ocument !ecribing ne& #eature in Objective-C 2.
200=-0<-20 Correcte! minor t$pographical error.
200=-02-0/ Clari#ie! the !icuion o# en!ing meage to nil.
2000-12-0- Clari#ie! the !ecription o# Co!e Liting <-<.
2ove! the !icuion o# memor$ management to Q2emor$ 2anagement
Programming 9ui!e #or Cocoa.Q
2000-0--2<
2000-0.-0. Correcte! minor t$pographical error.
2000-02-0= Correcte! minor t$pographical error.
2000-01-10 Clari#ie! ue o# the tatic peci#ier #or global variable ue! b$ a cla.
10?
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
*E5,',O( -,'TO*+
8ocument ;eviion 7itor$
/ate (otes
Clari#ie! e##ect o# en!ing meage to nilL note! ue o# Q.mmQ e'tenion to
ignal Objective-CKK to compiler.
200--10-0.
200--0.-0/ Correcte! t$po in language grammar peci#ication an!mo!i#ie! a co!e e'ample.
Correcte! the grammar #or the protocol-!eclaration-lit !eclaration in I?'ternal
8eclarationJ.
Clari#ie! e'ample in I4ing CKK an! Objective-C intance a intance variableJ.
;emove! #unction an! !ata tructure re#erence. A!!e! e'ception an!
$nchroni)ation grammar. 2a!e technical correction an! minor e!itorial
change.
200.-0/-<1
2ove! #unction an! !ata tructure re#erence to Objective-C Runtime Reference.
A!!e! e'ample o# threa! $nchroni)ation approache to I3$nchroni)ing Threa!
?'ecutionJ.
Clari#ie! &hen the initia&i@e metho! i calle! an! provi!e! a template #or
it implementation in IInitiali)ing a Cla ObjectJ.
A!!e! e'ception an! $nchroni)ation grammar to I9rammarJ.
;eplace! confor+s1o: &ith confor+s1o>rotoco&: throughout !ocument.
200.-02-02 Correcte! t$po in IAn e'ception han!lerJ.
200<-0,-10 Correcte! !e#inition o# id.
8ocumente! the Objective-C e'ception an! $nchroni)ation upport available
in 2ac O3 H verion 10.< an! later in I?'ception 7an!ling an! Threa!
3$nchroni)ationJ.
200<-0/-1.
8ocumente! the language upport #or concatenating contant tring in
ICompiler 8irectiveJ.
2ove! I2emor$ 2anagementJ be#ore I;etaining ObjectJ.
Correcte! the !ecription #or the ?var tructure an! the o$%c*ivar*&ist
tructure.
Change! the #ont o# function result in c&ass*get?nstance4ethod an!
c&ass*getC&ass4ethod.
Correcte! !e#inition o# the term conform in the gloar$.
Correcte! !e#inition o# +ethod*getArgu+ent?nfo.
;ename! #rom #nside Mac OS 1 .he Objective-C Programming 0anguage to .he
Objective-C Programming 0anguage.
110
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
*E5,',O( -,'TO*+
8ocument ;eviion 7itor$
/ate (otes
8ocumente! the language upport #or !eclaring contant tring. Ai'e! everal
t$pographical error. A!!e! an in!e'.
200<-01-01
2ac O3 H 10.1 intro!uce a compiler #or Objective-CKK% &hich allo& CKK
contruct to be calle! #rom Objective-C clae% an! vice vera.
2002-0--01
A!!e! runtime librar$ re#erence material.
Ai'e! a bug in the Objective-C language grammar* !ecription o# intance
variable !eclaration.
4p!ate! grammar an! ection name throughout the boo+ to re!uce
ambiguitie% paive voice% an! archaic tone. ;etructure! ome ection to
improve coheivene.
;ename! #rom Object Oriented Programming and the Objective-C 0anguage to
#nside Mac OS 1 .he Objective-C Programming 0anguage.
111
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
*E5,',O( -,'TO*+
8ocument ;eviion 7itor$
112
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
*E5,',O( -,'TO*+
8ocument ;eviion 7itor$
abstract class A cla that* !e#ine! olel$ o that
other clae can inherit #rom it. Program !on*t ue
intance o# an abtract claL the$ ue onl$ intance
o# it ubclae.
abstract superclass 3ame a abtract cla.
a!opt In the Objective-C language% a cla i ai! to
a!opt a protocol i# it !eclare that it implement all
the metho! in the protocol. Protocol are a!opte!
b$ liting their name bet&een angle brac+et in a
cla or categor$ !eclaration.
anon:"ous object An object o# un+no&n cla. The
inter#ace to an anon$mou object i publihe!
through a protocol !eclaration.
App&it 3ometime calle! !((lication %it. A Cocoa
#rame&or+ that implement an applicationM uer
inter#ace. AppNit provi!e a baic program tructure
#or application that !ra& on the creen an! repon!
to event.
as:nchronous "essage A remote meage that
return imme!iatel$% &ithout &aiting #or the
application that receive the meage to repon!. The
en!ing application an! the receiving application act
in!epen!entl$% an! are there#ore not in $nc.
Compare $nchronou meage.
categor: In the Objective-C language% a et o#
metho! !e#inition that i egregate! #rom the ret
o# the cla !e#inition. Categorie can be ue! to plit
a cla !e#inition into part or to a!! metho! to an
e'iting cla.
class In the Objective-C language% a protot$pe #or a
particular +in! o# object. A cla !e#inition !eclare
intance variable an! !e#ine metho! #or all
member o# the cla. Object that have the ame
t$pe o# intance variable an! have acce to the
ame metho! belong to the ame cla. 3ee alo cla
object.
class "etho! In the Objective-C language% a metho!
that can operate on cla object rather than intance
o# the cla.
class object In the Objective-C language% an object
that repreent a cla an! +no& ho& to create ne&
intance o# the cla. Cla object are create! b$ the
compiler% lac+ intance variable% an! can*t be
taticall$ t$pe!% but other&ie behave li+e all other
object. A the receiver in a meage e'preion% a
cla object i repreente! b$ the cla name.
Cocoa An a!vance! object-oriente! !evelopment
plat#orm in 2ac O3 H. Cocoa i a et o# #rame&or+
&hoe primar$ programming inter#ace are in
Objective-C.
co"pile ti"e The time &hen ource co!e i
compile!. 8eciion ma!e at compile time are
contraine! b$ the amount an! +in! o# in#ormation
enco!e! in ource #ile.
con9or" In the Objective-C language% a cla i ai!
to con#orm to a protocol i# it Eor a uperclaF
implement the metho! !eclare! in the protocol.
An intance con#orm to a protocol i# it cla !oe.
Thu% an intance that con#orm to a protocol can
per#orm an$ o# the intance metho! !eclare! in the
protocol.
!elegate An object that act on behal# o# another
object.
!esignate! initiali;er The init!!! metho! that
ha primar$ reponibilit$ #or initiali)ing ne& intance
o# a cla. ?ach cla !e#ine or inherit it o&n
!eignate! initiali)er. Through meage to se&f%
other init!!! metho! in the ame cla !irectl$ or
11@
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
9loar$
in!irectl$ invo+e the !eignate! initiali)er% an! the
!eignate! initiali)er% through a meage to super%
invo+e the !eignate! initiali)er o# it upercla.
!ispatch table The Objective-C runtime table that
contain entrie that aociate metho! elector &ith
the cla-peci#ic a!!ree o# the metho! the$
i!enti#$.
!istribute! objects An architecture that #acilitate
communication bet&een object in !i##erent a!!re
pace.
!:na"ic allocation A techni@ue ue! in C-bae!
language &here the operating $tem provi!e
memor$ to a running application a it nee! it% intea!
o# &hen it launche.
!:na"ic bin!ing 1in!ing a metho! to a
meageGthat i% #in!ing the metho! implementation
to invo+e in repone to the meageGat runtime%
rather than at compile time.
!:na"ic t:ping 8icovering the cla o# an object
at runtime rather than at compile time.
encapsulation A programming techni@ue that hi!e
the implementation o# an operation #rom it uer
behin! an abtract inter#ace. It allo& the
implementation to be up!ate! or change! &ithout
impacting the uer o# the inter#ace.
event The !irect or in!irect report o# e'ternal activit$%
epeciall$ uer activit$ on the +e$boar! an! moue.
9actor: 3ame a cla object.
9actor: object 3ame a cla object.
9or"al protocol In the Objective-C language% a
protocol that* !eclare! &ith the @protoco& !irective.
Clae can a!opt #ormal protocol% object can
repon! at runtime &hen a+e! i# the$ con#orm to a
#ormal protocol% an! intance can be t$pe! b$ the
#ormal protocol the$ con#orm to.
9ra"eor< A &a$ to pac+age a logicall$ relate! et
o# clae% protocol% an! #unction together &ith
locali)e! tring% online !ocumentation% an! other
pertinent #ile. Cocoa provi!e the Aoun!ation
#rame&or+ an! the AppNit #rame&or+% among other.
i! In the Objective-C language% the general t$pe #or
an$ +in! o# object regar!le o# cla. id i !e#ine!
a a pointer to an object !ata tructure. It can be ue!
#or both cla object an! intance o# a cla.
i"ple"entation The part o# an Objective-C cla
peci#ication that !e#ine public metho! Ethoe
!eclare! in the cla* inter#aceF a &ell a private
metho! Ethoe not !eclare! in the cla* inter#aceF.
in9or"al protocol In the Objective-C language% a
protocol !eclare! a a categor$% uuall$ a a categor$
o# the NS#$%ect cla. The language give e'plicit
upport to #ormal protocol% but not to in#ormal one.
inheritance In object-oriente! programming% the
abilit$ o# a upercla to pa it characteritic
Emetho! an! intance variableF on to it ubclae.
inheritance hierarch: In object-oriente!
programming% the hierarch$ o# clae that* !e#ine!
b$ the arrangement o# uperclae an! ubclae.
?ver$ cla Ee'cept root clae uch a NS#$%ectF
ha a upercla% an! an$ cla ma$ have an unlimite!
number o# ubclae. Through it upercla% each
cla inherit #rom thoe above it in the hierarch$.
instance In the Objective-C language% an object that
belong to Ei a member o# F a particular cla.
Intance are create! at runtime accor!ing to the
peci#ication in the cla !e#inition.
instance "etho! In the Objective-C language% an$
metho! that can be ue! b$ an intance o# a cla
rather than b$ the cla object.
instance variable In the Objective-C language% an$
variable that* part o# the internal !ata tructure o#
an intance. Intance variable are !eclare! in a cla
!e#inition an! become part o# all object that are
member o# or inherit #rom the cla.
inter9ace The part o# an Objective-C cla
peci#ication that !eclare it public inter#ace% &hich
inclu!e it upercla name% intance variable% an!
public-metho! protot$pe.
,nter9ace 2uil!er A tool that let $ou graphicall$
peci#$ $our application* uer inter#ace. It et up the
correpon!ing object #or $ou an! ma+e it ea$ #or
$ou to etablih connection bet&een thee object
an! $our o&n co!e &here nee!e!.
11D
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
8LO''A*+
lin< ti"e The time &hen #ile compile! #rom !i##erent
ource mo!ule are lin+e! into a ingle program.
8eciion ma!e b$ the lin+er are contraine! b$ the
compile! co!e an! ultimatel$ b$ the in#ormation
containe! in ource co!e.
"essage In object-oriente! programming% the
metho! elector EnameF an! accompan$ing
parameter that tell the receiving object in a meage
e'preion &hat to !o.
"essage e=pression In object-oriente!
programming% an e'preion that en! a meage
to an object. In the Objective-C language% meage
e'preion are encloe! &ithin @uare brac+et an!
conit o# a receiver #ollo&e! b$ a meage Emetho!
elector an! parameterF.
"etho! In object-oriente! programming% a
proce!ure that can be e'ecute! b$ an object.
"ute= 3hort #or mutual e/clusion sema(hore. An
object ue! to $nchroni)e threa! e'ecution.
na"espace A logical ub!iviion o# a program &ithin
&hich all name mut be uni@ue. 3$mbol in one
namepace !o not con#lict &ith i!enticall$ name!
$mbol in another namepace. Aor e'ample% in
Objective-C% the intance metho! o# a cla are in a
uni@ue namepace #or the cla. 3imilarl$% the cla
metho! o# a cla are in their o&n namepace% an!
the intance variable o# a cla are in their o&n
namepace.
nil In the Objective-C language% an object id &ith a
value o# 0.
object A programming unit that group together a
!ata tructure Eintance variableF an! the operation
Emetho!F that can ue or a##ect that !ata. Object
are the principal buil!ing bloc+ o# object-oriente!
program.
outlet An intance variable that point to another
object. Outlet intance variable are a &a$ #or an
object to +eep trac+ o# the other object to &hich it
ma$ nee! to en! meage.
pol:"orphis" In object-oriente! programming% the
abilit$ o# !i##erent object to repon!% each in it o&n
&a$% to the ame meage.
proce!ural progra""ing language A language%
uch a C% that organi)e a program a a et o#
proce!ure that have !e#inite beginning an! en!.
protocol In the Objective-C language% the !eclaration
o# a group o# metho! not aociate! &ith an$
particular cla. 3ee alo #ormal protocol% in#ormal
protocol.
receiver In object-oriente! programming% the object
that i ent a meage.
re9erence counting A memor$-management
techni@ue in &hich each entit$ that claim o&nerhip
o# an object increment the object* re#erence count
an! later !ecrement it. :hen the object* re#erence
count reache )ero% the object i !eallocate!. Thi
techni@ue allo& one intance o# an object to be
a#el$ hare! among everal other object.
re"ote "essage A meage ent #rom one
application to an object in another application.
re"ote object An object in another application% one
that* a potential receiver #or a remote meage.
runti"e The time a#ter a program i launche! an!
&hile it* running. 8eciion ma!e at runtime can be
in#luence! b$ choice the uer ma+e.
selector In the Objective-C language% the name o# a
metho! &hen it* ue! in a ource-co!e meage to
an object% or the uni@ue i!enti#ier that replace the
name &hen the ource co!e i compile!. Compile!
elector are o# t$pe S;=.
static t:ping In the Objective-C language% giving the
compiler in#ormation about &hat +in! o# object an
intance i% b$ t$ping it a a pointer to a cla.
subclass In the Objective-C language% an$ cla that*
one tep belo& another cla in the inheritance
hierarch$. Occaionall$ ue! more generall$ to mean
an$ cla that inherit #rom another cla. Alo ue!
a a verb to mean the proce o# !e#ining a ubcla
o# another cla.
superclass In the Objective-C language% a cla that*
one tep above another cla in the inheritance
hierarch$L the cla through &hich a ubcla inherit
metho! an! intance variable.
11A
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
8LO''A*+
s:nchronous "essage A remote meage that
!oen*t return until the receiving application #inihe
repon!ing to the meage. 1ecaue the application
that en! the meage &ait #or an ac+no&le!gment
or return in#ormation #rom the receiving application%
the t&o application are +ept in $nc. Compare
a$nchronou meage.
11E
2010-12-08 B C 2010 Apple ,nc4 All *ights *eserve!4
8LO''A*+

You might also like