Вы находитесь на странице: 1из 300

0 B J E C T IV E - C

iOS MacOS
" Objective-C
-f- Xcode Apple
H iOS Cocoa

n e ro

^nm vp'

Aaron Hillegass

Objective-
Programming
BIG NERD RANCH GUIDE

OBJECTIVE-C

iOS MacOS

^
* -
--

2012

32.973.2-018.1
004.43
X45

.
X45

Objective-. iOS MacOS. .: , 2012. 304 ..


ISBN 978-5-459-01567-6
iOS Mac? ,
Objective-,
!
IT- Big Nerd
Ranch, Objective- 1-.
Xcode 4.2, IOS 5 Mac OS X 10.7 Lion
, ,
Objective-
Apple.
32.973.2-018.1
004.43

The Big Nerd Ranch. .



.
, , ,
. , ,

, .
Al rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, etectronic or
mechanical, indudlng photocopying, recording or by any information storage retrieval system, without permission from
PKer Pubhshing House. Russian language edition published by Plter Publishing House.

fSBH 97&032l706287 .

KAH97&v45&01567*6

Authorized translation from the Englteh language edition, entitted Objective<


Programming: The Big Nerd Ranch Guide 1st Edltton, 9780321706287
by Aaron HillegaM, published by The Big Nerd Ranch (Aaron Hiltegass),
2011 The Big Nerd Ranch (Aaron Hiilcgass)
> OCX) , 2012
, , 2012

. . .. ......................................................................................................
I. . . . . . ............. ...................................................................... .....
1. . . ...................... ............................................................... 12
Objective-C........................................................................................................ ...
........................................................................................ 13
.......................................................................................14
2. ............................................................................. 15
Apple................................................................ 15
Xcode........................................... ....................................................16
?................ . .......................................................................................18
? ................................................. ...................................21
?.......................................................................................23
....................................................................................... ...... 25
II. ............................................................27
3. ...................................... .. ..................................... 28
.................................................. ................................................. ......................29
........... .......................................................................... 30
.................................................................................................. ...........32
4. tf/else....................................................................... .. * . ..............................33
.................................................................... ......................35
else if........................................................................................................................... 36
: () ............................. * 37
........................................................................................................... 38
5. .. ........................................................................................... ^9
?....................................................................... * 39
?............................................................... 40

.......................................
, .........................................

.................

............................................................................................... 11111
................................................................
return............................................................................................................... g2
.................................................... '
.....................................................................................................

6 . .............................................................................................
f ^ 7_ ^
printf().............................................................................................................................
...................................................................................................... ...
..........................................................................................63
.............................................................................................................

7. ............................................................................................ ................ 65
while................... ............................................................................................ .. 6 6
for............................................................................................. ...........................67
break........................................................................................................................ . . 6 8
continue........................................................................................... .. .....................69
do-while............................................................. .................................................. 71
.............. .. . ........................... ................. I ....................
............ ......................... ....
8. ............... .................
................. .... .................... .. ...................... ........................... ..
................. . . . T .................. ...............................
. . . . . . . . . . .............................................
NULL ....................................... ..........................................................................................
............................................
.................................................... .. . . . . . . . . . . . . . . . .
9. ...................................................................

NULL.........................................................
10. ..................................................................................
..............................................................................................
11. .............................................................. .............................
I I I . Objective- Foundation . . .
12. ...................................

...........................
............................ !

id

......................................................... ..

....................................

13. ........................................................................ . ..................... 100


....................................................................... 100
................................................................................. 101
nil........................................................................................ 102
.. .. ..................................................................................................... 103
14. NSString.................................................................................. .................... 104
...............................................................................................................105
15. NSArray . . . . ................................................................ .......................... 106
NSMutableArray..................................... ..................................................................109
...............................................................................................................110
16. . . . . ......................................................... 112
.............................................................................................113
.............. ................................................................................... .... 116
.............................................................................117
17. ...................................................................................... 119
.................................................................. . .................. ....................122
................................... ...................................................................124
..................................................................... ............................ ........ . 124
................................................................................................................ 127
18. .............................................................................................. 128
........................ ..................................... ............................. *32
.............. .............................. . . . ! . ......................................... ...........133
19. .................. .... ......................... 135
A R C ............................. ..................................................... 137
Employee ......................................... I4
.................................................................... . . ? . . . ................. * 1 4 4
20. . ................. .. .........................................**
14ft
...................................................................................... . ** *
............................................................... .................. ............................ ..... * *
............................................................................................" *
: ARC............................. 153
......................................................................................I *
21. ................................................................... ............................J
NSArray/NSMutableArray.............................................................................................
.............................................................................................
............................................................................................ .......................j - j
................................................................................................................... 1 2

NSSet/NSMutableSet....................................................................................................... ^
...................................................................................................................................................................................................

................................................................ .. .......................... . - n i!.............. ................................ ..............................* ........... * ...........^-


.. , * ................... ........................................... * ..............................


22. ...............................................
...................................... .....................................
.......................................... ................................... ...
enum................................................................................. .............................
|
23. NSString NSData.........................
NSString ......................................................... ....................... ...
i
NSError............................................................................... ' ' ' .................. ...
;
NSString......................... ......................... ...
NSData .............................................
................ 1 7 8
NSData ..........................................................
........ *7 9
24. ...................................................... ..........
'^ ^ *
/........................................................................... ; ; . | ?
...........................................................................
^
........................................................................................................
?............................................................................................ ...
....................................................... ...
25. ................................................................................................
2. .................................................................................... 19 7
........................................................................................................... 200
W . ........................................................... 201
27. iOS.......................................................................... 202
iTahDoodle........................................................................ 203
BNRAppDelegate...................................................................................... ...............205
iTahDoodle......................................................................207
--...................... .......................................... 2 0 8
..........................................................................................2 1 0
.................................................................................... 2 1 1
iOS Simulator................................................................................. ^
214
..........................................................
.......................................................................................* j
............................................................ ..................................
g
: main()?..............................................* * * *
28. Cocoa.................. .............................. ...................*
BNRDocument.h................................................ '
1 ^ J
Interface Builder.............................................................. .............
BNRDocument.xib...................... .. ................. * * * ^ |
..................................................................... ' * * Z *3
MVC................................................................ .......... * *

BNRDocument.m............................................................. 2 3 6
........................................................................................ .................

18 3

V. O b je c tiv e -C .......... ............................237


29. init....................................................................................................238
in it............................................................................... 238
init..................................................................................239
................................................................. 241
initcapryMeHTaMH........................................................................................ 242
init.....................................................................................248
30. ...........................................................................................250
. . ....................................................................................... 251
............................................................................... 254
-...............................................................................255
31. ......................................................................... ............ 259
32. .................................................................................................. 261
......................................................................................262
. ................................................................................262
.................................................................263
..................... ............................................................ 264
typedef..................................................................................................................269
....................................................................................270
.......................................................................................... 270
...................................................................................................272
......................................................................................................... 272
VI. ..................... ................................. 2 7 5
33. ............................ ......................................... 2 7 6
........................................................................* 2 7 7
............................................................................ * 27^
.........................................................................28
........................................................................................................281
.................................................................................................
284
......................................................................................................
34. ................................................................................................^

dw ....7_.............................................................. 285

char * ................................................................................................................
7fiQ
......................................................................................
NSString ...........................................................
.....................................................................................................
35. ..........................................................................................
36. ............................................................
37. switch....................................................................................
............... 300
............. ...................... ............ .....................................
................................................................................

.
,
, .
(Mikey Ward) ,
iOS, .
,
.
, Objective-, ,
.
(Scott Ritchie), (Mark Fenoglio),
(Brian Hardy), (Christian Keur)
(Alex Silverman).
(Susan Loper)
, ,
, .
.
(James Majors), (Mark Dalrymple),CKorr
(Scott Steinman), (Bart Hoffman),
(Bolot Kerimbaev) (Nate Chandler).
(Ellie Volckhausen)
.
(Chris Loper) InteiligentEnglish.com
EPUB Kindle.
Pearson Technology Group
*

^mm

. iOS
Mac OS X, ( ,
). (iOS Programming: The
Big Nerd Ranch Guide Programming for Mac OS X),
. ? .
, . ?
iOS Mac, ,
.
, .
.
, - .
Objective-, ,
.
-
. ,
. ,
.

.

Objective-C
,
, ,
. ,

13

.
.
,
( ).
( ).
, (
iMac
, PowerBook). ,
,
.

,
.
,
( )
.
. ,
.
1970- AT&T.
Unix, Mac OS X nLinux,
.
Windows .
Objective- ,
- . Objective-C
Apple iOS Mac OS X.


Objective-C
, iOS Mac.
?
Objective-C . , ,
Objective-C ,
. ,
Objective-C.
, Mac.
,
. .
. -

14

, , - 1
.
,
.
.
.
, .
,
. ,
.
, ,
.
Big Nerd Ranch ,
. http./ /
forums.bignerdranch.com/.
,
, . ,
,
. .
.


, . ,
, .
.
,
- . , -
;
. ,
,
.
, .
,
, () . ,
.
,
(Scott Rosenberg) Dreaming in Code.
.

, , . ,
, iPhone iPad.
:
Apple;
;
, ,
.

Mac.

Apple
Mac OS X (Macintosh) iOS (iPhone
iPad) Apple.
http://developer.apple.com/
Mac App Store.
/Developer
.
Mac OS X
iOS.

Xcode /Dez>eloper/Applications. (
Xcode -; .)

16

Xcode

Xcode (ID E , Integrated Development


Environment) Apple. , Xcode
,
Xcode.
:
.
; .

; .
, . ,
Mac 60 . ,
- . , ,
, pboard.
/, pboard .

;
.
,
,
.
, Xcode ,
, .

. Xcode .
Xcode, File New, New Project...
, Xcode
. ,
.
Mac OS X Application. Command Line Tool
.
Next.
AGoodStart.
,
. BigNerdRanch
. ,
. , ,
Use Automatic Reference Counting .

Xcode

Uudtaf

C h o c se a t w n p t a t i f o r y o u r n e w p ro J e c c

Application
Framework & Ubr*ry j
Other

.............. 1 Appiictfton

^MatOSX

coco
*-Apptescript

FrameworJc Ubr*ry
Application Wug-ln
System Plug->n
Other

Command Une Tool


This ttm e ln e builds a command-line tool.

Previous

. 2.1.

. 2.2.

18

Next.
, . ^
, .
Create.
*
. :
-
.
( ? , O bjectiv e-
. ,
O b jectiv e-C .)

?

A 6oodS tart.

Build Phas*s
ftutes
&* *

^ACoodStart
maln.c
ACoodSurtl
.Produas

!..,^,),>,: *.Qr
i Setting

*ACoodStan

^^^&^^^
^
'^^^^^^

Additional SDKs
f Ati>tttcturcs
{ Base SOK
| t Bu)ld Active Architecture Onlv
Oebug
i
Release
i Supported Platforms
( Valld Architectures

64-bitintei - S
Latest Mac OS X (Mac OS X 10.6) I
<Mu>t>pie values>
Yes J

No;

macosx
(386 *86_64

i-rtTBM
i^M
iSM
ftviui!w-arfr^M
^rt^tt^rt^^^^^^^^^^^&

btflld
Build Products Path
buitd
Intermediate Build Files Path
<Muhiple valus>
Per-conftguration Build Products Path
bulid/O*bug
Debug
bulid/Reiease
Release
Per~<onftguratk>n intermediate 8uild FI , <Muktpie value>
buiM/AGoodSurt.burid/Debug
Debug
build/ACoodSiart-bulkt/Reiease
Release
/V*r^a*ders/rtj/nii+H*KFbWCt^iMrt^
Prc<ompiled Headert Cache Path

normal

VaMate kfUn91

. 2.3. AGoodStart

19

: Mac OS X
,
,
.
.
main.c
. ( main.c,
AGoodStart, .)
1K S S S

*fj[ ACoodStart-xced<proj .~~ .fg] malw.c

|||

,,&:jf
*tSAA3_aA 7
7

^^2^ ^5 ^ ^1^^^^^ j
*4"* ^ ^ ^ ^ ^ ^
*<0
';
ACoodScart
1 urpet. 05 X SDK 10.6
J AGoodStart

.......

% ,> ^

//
//
//
//
//

. - . ! w

- ^ #

: . . ': ^ R 1

r.p n * r f i

m ain .c
A 6oodS tart

C re a te d by Aaron H ille g a s s on 9 /1 2 /1 1 .
C o p y rig h t ( ) 2011 Big Nerd Ranch. A ll r ig h ts reserv ed .

//
# in c lu d e < s td io .h >
i j i n t main ( i n t a r g c , c o n s t c h a r

1'

a r g v [] )

/ / i n s e r t code h e r e . . .
p r i n tf ( * 'H e l lo , W o rld !\n " );
re tu rn 0;

[+ i @ V S M

. 2.4. main.c AGoodStart


:
main.c. main.c
main.
,
. .
Objective-C main .
#include < s td io .h >
in t main ( i n t a rg c , const char * a r g v [ ]) {
/ / in s e r t code h e r e .. .
p r in t f ( " H e llo , W o rld !\n " );
re tu rn 0 ;

20

:
.
, I
.
. , , .
, ,
. ,
,
, :
, , .
Objective-
:
//, ,

, . insert code
here..> Apple.
,
/* */ , !
.
.
, ,
.
; ,
.
, !
, . , * |
;
(;). ( .)
,
.
, Xcode . *
, , ,
, Xcode ,
. Xcode
.
maxn.c .
. ({ }),
naln. , .

21

main.c, ,
. main ,
. ,
. , ,
.
#include <stdio.h>
in t main (in t argc, const char * argv[])

//

p r i n t f ( " I t was the best of tim e s .\n " );


p r i n t f ( " I t was the worst of tim e s .\n " );
/* ?
, . * /

return 0j

>
( : , ,
. ,

. ).
, , Xcode
. .

.
, .
Xcode,
Xcode.)
. Xcode
, . (
, .) :
Xcode ,
.
(, ).
,
.
, Xcode
() .

?
main.c ,
; .

22

: Xcode , . -'|
Xcode .
.
Xcode.
.
, ^
.
P , weuian*L
. Xcode (log) .
.
. ,
p r i n t f ( " I t was the best o f t i m e s . \ n " ) ;

It was the best oftimes. .


,
. ,
Play iTunes DVD-. , Build and then run
the current scheme. Xcode : ,
.
,
:

, :

? .
. Xaxie

23

, , , . ,
Run. ,
.
'|{,!
( ,
. ,
, . ,
.)
,
Debug AG oodStart. ,
.
.
. !
GNU gdb 6.3.50-20050815 (Apple version gdb-1705) (Tue 3ul 5 07:36:45
UTC 2011)
Copyright 2004 Free Software Foundation, In c .
DB is fre e softw are, covered by th e GNU General Public License, and
you are welcome to change i t and/or d is tr ib u t e copies o f i t under
certain con d itio n s.
Type "show copying" to see th e c o n d itio n s .
There is a b so lu tely no w arranty f o r GDB. Type show warranty" fo r
d e ta ils .
This GDB was configured as " x 8 6 _ 6 4 -a p p le -d a rw in " .tty /d e v /tty s 0 0 1
[Switching to process 2723 thread 0x0]
I t was the best o f tim es.
I t was the worst o f tim es.

( Apple
LLDB. GDB, .
GDB, , Xcode
LLDB. ; !)

?
, .
. . , .
; main.
p r l n t f . ,
. ( , p r i n t f ,
5).

24

:
. . :
1970-
.
. , .
,
.
*

Baked Chicken

III

In a shallow dish whisk together


milk, egg, oil, salt and pepper, i
I

Set rack abput 6 inches from


heat and preheat broiler.

Dip chicken in milk mixture, coat|


with bread crumbs, put in in a J
foil like broiler pan

Broil chicken until cooked


through, about 7 minutes on
each side.

j
j
<
I
I
I
I

. 2.5.

.
.
.
?
^ ),
(
). ,
Xcode, Run.
; .

, main.
main . ,
rnain p rin tf. ( ,
, 5.)

25

He
, :
, , . ,
, . .
.
. ,
. ,
. :
? , ?
, ,
, , , .
, ,
, .
.
. ,
,
.
, .
.
.
. , .
; ,
.

,
.
, , .

!
, , .
,
. :
,
,
Objective-C.

: -
. , ,
: 14,2 . ,
: weight () = 14,2. ,
, (15 + 15
), .

. 3.1. ,
,
. ,
, .
(, cookingTlme ( )) (, ).
,
(, 228.0).

29


. :
flo a t weight;

f l o a t weight.
.

. :

. ,
, .
, -
: .
, ( )
.
.
.

short, int, long


. short
long, int - .
long
, short

float, double

float
,
. float
: . ,
346,2 3,462 x 102. double
;
,

<
har

A\

/ u

,
- , 'a'

30

. (*).
, , int *,
,
int.
, int,
.
,
...

struct

( )
.
struct. ,
GeoLocation,
,
: .


. ,
.


Xcode; .
AGoodStart, .
(File New New Project...).
Command Line Tool, Turkey.
main.c .
main.c , :
#include <stdio.h>
in t main ( in t argc, const char * argv[])

/ / 'w eig h t' f lo a t


flo a t weight;
/ /
weight 14.2;

31

//

printf("The turkey weighs % f.\n", weight);


// flo a t

flo a t cookingTime;
//
//
// '* ' ' '

cookingTime = 15.0 + 15.0 * weight;


//

printf("Cook i t fo r %f m inutes.\n", cookingTime);


//

return 0;

>
. Run
Xcode, Command+R.
, .
Debug Turkey, .
:
The turkey weighs 14.200000.
Cook i t for 228.000000 minutes.

i | , .
main.c Xcode .
, .
:
float weight;

w eight flo a t .
:
weight * 14.2;

. ,
14.2.

:
float weight > 14.2;

:
cookingTime 15.0 + 15.0 * weight;

32

= ~ , !
(). , -1
= .
, :
w eight = 1 4 .2 ;

14. 2.*,. . ,-?>.'; ^ ^^^^^


.
.
,
.

TwoFloats.
main() f lo a t
* 3.14 42.0.
double f lo a t .
p r in t f( ) . ,
.

if/else


.
? , Submit
? , ,
.
if /e ls e ,
:
i f () {
/ / , (tru e )
} else {
/ / , (fa ls e )

>

.
, , .
if /e ls e :
flo a t truckM eight = 34563.8;
/ / ?
i f (truckWeight < 40000.0) {
p r in t f ( " It is a lig h t tru c k \n ");
} else {
p r in t f ( " It is a heavy tru c k \n ");

>

e ls e , :
flo a t truckW eight * 34563.8;
/ / ?

&

34

4 if/else

i f (truckWeight < 40000.0) {


p rin tf(" It is a lig h t tru ck \n ")j

:
true () fa ls e (). , false
0, true.
< .
, 1 (
).
, 0 (
).
. . 4.1
, (
, ).

4.1.

< -

>

<-'--

>=

== -

71^ "

== :
== . ,
= . ,
- , = ==.
=
>.
.
, ,
, 0 40 000?
AND (&&):

35

i f ((truckW eight > 0 .0 ) && (tru ckW eig ht < 4 0 0 0 0 .0 )) {


p rin tf(" T ru c k weight is w ith in le g a l ra n g e .\n " );

>
. 4.2.
4.2.

AND true ,
true

&&

OR false ,
false
NOT true false,

( , ,
OR Objective-C ,
.)
NOT ( ! ) ,
:
/ / ?
i f (!((tru c kW eig h t > 0 .0 ) && (truckW eight < 4 0 0 0 0 .0 ))) {
p rin tf(" T ru c k weight is not w ith in le g a l ra n g e .\n " );


, .

:
BOOL isNotLegal = ! ((truckW eig h t > 0 .0 ) && (truckW eight <
i f (isNotLegal) {
p rin tf("T ru c k weight is not w ith in le g a l ra n g e .\n " );

4 0 0 0 0 .0 ));

>

, tr u e fa ls e ,
. in t. Objective-C
BOOL,
. (, BOOL

.) BOOL ,
:
#include <objc/objc.h>

: ,
, ,
. , :
BCX)L isNotLegal = !(.(truckWeight > 0.0) && (truckWeight < 40000.0));
i f (isNotLegal)
p rin tf("Tru ck weight is not w ithin le g a l range.\n");

, ,
:
BOOL isNotLegal = !((truckW eight > 0.0) && (truckWeight < 40000.0));
i f (isNotLegal) {
p rin tf("T ru ck weight is not w ithin le g a l range.\n");
printf("Impound tru c k .\ n ");

>

- ^

? , :
BOOL isNotLegal = !((truckW eight > 0.0) && (truckWeight < 40000.0))j
i f (isNotLegal)
p rin tf("T ru ck weight is not w ithin le g a l range.\n");
printf("Impound tru ck .\ n ");

p rin tf
, .
, , i f
. , printf
. ( ? , ,
; .)

else if
?
e lse if. ,
: (floating), (light)
(heavy).
i f (truckWeight <*> 0) {
p r in t f ( "A flo a tin g truck\n");
} else i f (truckMeight < 40000.0) {

: ()

37

p rin tf(" A li g h t tr u c k \n " ) ;


} else {
p r in tf( " A heavy tr u c k \ n " ) ;

>
e ls e i f .
,
true. .
, . ,
,
,
. e ls e ,
, ,
.

: ()

i f e ls e
. :
in t minutesPerPound;
i f (isBoneless)
minutesPerPound = 15;
else
minutesPerPound = 20;

,
, , ?. ( ).
in t minutesPerPound = isB oneless ? 15 : 20;

. i f e ls e
. ?
, ?
.
,
i f e lse . ,
.
- , ,
!

38

4 if/else

:
in t i * 20;
in t j * 25;

int k ( 1 > j ) ? 10 : 5;
i f ( 5 < j - k ) { / /
printf("The f ir s t expression is true.
} else i f ( j >i ) { / /
printf("The second expression i s true
} else {
printf("Neither expression i s tru e." )
>

3 , : , ,
, .
. .
.
,
, ,
. , ,
.

?
, ,
. ,
,
,
.
:
C la s s C e rtific a te s .
:
in t main (in t argc, const char * a rg v [])

{
printf("M ark has done as much Cocoa Programming as
X could f i t in to 5 d a y s\n ");
p rin tf(''B o has done as much O bjective-C Programming as
I could f i t in to 2 d a y s\n ");

() &

40

printf("M ike has done as much Python Programming as


I could f i t in to 5 d a y s\n ");
printf("T ed has done as much iOS Programming as
I
could f i t in to 5 d a y s\n ")j
retu rn 0;

>
?
? , .
(
p r i n t f ) , ,
.

, ; , .
main.c C la s s C e r tif ic a te s
main. c o n g r a tu la te S tu d e n t.
#include < std io .h >
void congratulateStudent(char *student, char *course, in t numDays)

{
printf("%s has done as much %s
Programming as I could f i t in to %d days.\n",
student, course, numDays);

>
( , %s %d? ;
.)
main,
:
int main (int argc, const char * argv[])

{
congratulateStudent("Mark", "Cocoa", 5)j
congratulateStudent("Bo", "Objective-C", 2);
congratulateStudent("Mike", "Python", 5)j
congratulateStudent("Ted", "iOS", 5);
return 0;

>

*5 |

. , ,
.

41

Xcode ;
.
. -
'congratulateStudent'. ,
.
.
, , .
Mark has done as much Cocoa Programming as I could f i t in to 5 days.
Bo has done as much O bjective-C Programming as I could f i t in to 2 days.
Mike has done as much Python Programming as I could f i t in to 5 days.
Ted has done as much iOS Programming as I could f i t in to 5 days.

, .
. (
) .
( , , ).
. ,
.
void c o n g ra tu la te S tu d e n t(c h a r * s tu d e n t, char *course, i n t numDays)

: .

.
vo id ? ,
. ,
void.
.
( ) main.
congratulateStudent ,
.
. ,
.
. c o n g ra tu la te S tu d e n t
: "Mark", "Cocoa" 5.
co n g ratu lateS tu d en t("M ark ", "Cocoa", 5 );

. c o n g r a tu la t
eStudent 5 (numOays).

t ( ) . 5 , numOays
Int... .
. . ,;, .

numDays congratulateStudent ( ) 5
numDays
. , , ,
.
C la s s C e r t if ic a t e s
. ?
? , .
. ,
, .
, Xcode , Xcode
.
.
, ,
. |
,
, .

ClassCertificates - OassCertificates.xcodeproj
Xcode

...,.,..
. _ .

i Si*

-~"V.y

f ^_j GassCertifitates

te) mainx
CUssCertfKxes.l

^J Products

utes

9
PROjCCT
'f^ GassCcrtlficates
TARCrTS

____:______...,,...w^j . J+*Jk
Build Phases
Build Rules
f lP |; ffigfe jflfj^*
\ClassCertificates
;5etting
| TAppie LtVM(Offlpl^r irQ- Wimlnes
Yes :
O>eckSwitchStatements
~aurCharacter Literals
No *
NO*
HiddenLocal Variables
mplkil Atomic Objective-Properties No t
Yes ;
mplicit Conversion to 32 Bit Type
No i
mplicit SignednessConversions
ncompieteObJectrveC Protocols
Yes *
nhibit All Warnings
No i
nJtto|izer Not Fully Bracketed
Mismatched Return Type
Yes
Missmg Bracesand Parentheses
Yes :
Missing Fields tnStructure Initializers NO
i BuifdScttfn9s

2o

MluiM MnvUMAl Fod.Qlflfc

+ i g| Qf <5

Modernize Prq^ct

.1

Md

Setttng

. 5.1.

:
, ,

43

. ,
.
.
, .
, - .
,
.
. , Xcode ,
.
, ,
. ,
C l a s s C e r t i f i c a t e s
. All Build
Settings. ,
Missing Function Prototypes No.


. ,
,
main .
, .
, ,
; , ,
. :
,,.
main . ,
main C la s s C e r t if ic a te s c o n g ra tu la te
Student, p r i n t f .

* ,
.
main ,
.
, , s le e p ,
, . -


Baked Chicken

!
I
I

4\

Seasoned Bread Crumbs

ln a shallow dish whisk together


milk, egg, oil, salt and pepper. !

Tear 3 slices of bread into pieces


and spread on cookie sheet.

Execute the Seasoned Bread


Crumbs recipe.

Mix olive oil, parsley flakes,


oregano, and garlic power.

Set rack about 6 inches from


heat and preheat broiler.

t
|

Drizzle on bread pieces


Dry in oven at 225 F for an hour

Dip chicken in milk mixture, coat!


with bread crumbs, put in in a J
foil like broiler pan
Broil chicken until cooked
through, about 7 minutes on
each side.

Crumble into crumbs.

!
|
4

. 5.2.

in t main ( i n t a rg c , co n st ch ar * a r g v [ ] )

{
co n g ratu lateS tu d en t("M ark ", "Cocoa", 5 );

sleep(2);
c o n g ra tu la te S tu d e n t("B o ", "O b jectiv e-C ", 2 );

sleep(2);
co n g ratu lateS tu d en t("M ik e", "PHP and PostgreSQL", 5 );

sleep(2);
co n g ra tu la te S tu d e n t("T e d ", "iO S", 5 );
re tu rn 0;

}
. (
.) ,
2- . - ,
main , sle e p
.
:
. ,
. ,
main, m a in ().
Baui . -
- : ,
Mac OS X, ,

45

. , Mac OS X
, .
; s lee p ( )
p r i n t f ( ) .
main.c stdio.h.
p r in tf () ,
. sleep()
stdlib.h. ,
sleep ():
#include <stdio.h>
#include < s td lib .h >

void congratulateStudent(char *student, char *course, in t numDays)

{
:

,
. ,
, .

.

, . ,
,
. , iOS Mac
OS X, 16.

,
.
, .
,
. , ,
. :
void showCookTimeForTur,key( in t pounds)

<

in t necessaryMlnutes 15 + 15 * pounds;

&

46

printf("Copk for %d minutes.\n", necessaryMinutes);

}
necessaryM inutes .
showCookTimeForTurkey()
.
pounds .
,
.
;
. ,
.
, .
, .
,
.
. ?
. ,
, . ( )
,
, . , ,
, .

. 5.3.

: .
^ * -

^*^ ^ *

47

, showCookTimeForTurkey() :
void show C ookTim eForTurkey(int pounds)

{
>

i n t n e c e s sa ry M in u te s = 15 + 15 * pounds;
p r in tf ( " C o o k f o r %d m i n u t e s .\ n " , n e c e s s a ry M in u te s );

i n t m a in ( in t a r g c , c o n s t c h a r * a r g v [ ] )

{
>

i n t t o ta lW e ig h t = 10;
i n t g ib le ts W e ig h t = 1 ; .
i n t tu rk e y W e ig h t = t o ta l W e ig h t - g ib le ts W e ig h t;
sh o w C o o k T im eF o rT u rk ey (tu rk ey W eig h t);
re tu rn 0;

, m ain() .
main() showCookTimeForTurkey(),
.
pounds 15?
showTurkeyCookTime()

main()

pounds = 9
necessaryMinutes = 150
totalWeight = 10
gibletsWeight = 1
turkeyWeight = 9

. 5.4.

, .
, showCookTimeForTurkey() ,
main() .
: pounds, showCookTimeForTurkey(), . ,
,
. turkeyWeight 9
showCookTimeForTurkey().
pounds .

48

? ?
. , 99 *
. BeerSong
main.c, ?
main():
# in c lu d e < std io .h >
void singTheSong(int numberOfBottles)

{
i f (numberOfBottles == 0) {
p rin tf("T h ere are simply no more b o ttle s o f beer
on the w a ll.\ n ");
} else {
printf("%d b o ttle s o f beer on the w a ll, %d b o ttle s of beer.\n"
numberOfBottles, numberOfBottles);
in t oneFewer = numberOfBottles - 1;
p rin tf("T a k e one down, pass i t around,
%d b o ttle s o f beer on the w a ll.\ n " ,
oneFewer);
singTheSong(oneFewer); // T h is fu n c tio n c a l l s i t s e l f !
p rin tf( " P u t a b o tt le in the r e c y c lin g ,
Xd empty b o t tle s in the b in .\ n " ,
num berOfBottles);

)
>

tT

i;, , ,

int main(int argc, const char * argv[])


{

? '^ f l H

singTheSong(99);

return 0;
>

: '.

" '.'^ -:^ -/"

. :
99 bottXes of beer on the waXX. 99 bottles of beer.
Take one down, pass l t around, 98 b o ttles o f beer on the walX.
98 bottles of beer on the waXX. 98 bottXes of beer.
Take one down, pass i t around, 97 bottXes o f beer on the waXX.
97 bottXes of beer on the waXX. 97 bottXes of beer.
t bottXes o f beer the waXX. 1 bottXes o f beer.
Take one down, pass l t around, 0 bottXes o f beer the waXX.

;j

49

There a re sim ply no more b o t t l e s o f b e e r on th e w a ll.


Put a b o t t l e
in th e r e c y c li n g , 1 empty b o t t l e s in th e b in .
Put a b o t t l e
in t h e r e c y c li n g , 2 empty b o t t l e s in th e b in .
Put a b o t t l e
Put a b o t t l e

in t h e r e c y c l i n g , 98 empty b o t t l e s in th e b in .
in t h e r e c y c l i n g , 99 empty b o t t l e s in th e b in .

, ?
singTheSongO numberOfBottles = 0
singTheSongQ numberOfBottles = 1

oneFewer = 0

singTheSongO numberOfBottles = 96
oneFewer = 95
singTheSongO numberOfBottles = 97
oneFewer = 96

singTheSongO numberOfBottles = 98
oneFewer = 97
singTheSongO numberOfBottles = 99
oneFewer 98
mainO

. 5.5.
-
, ,
. -,
: ,
? -, 6pai e , ,
( ).
u Xcode,
, .

50

,

m a in () ,
. BeerSong,
, There
simply no more bottles o fb e e r on th e wall.
? main.c
printf("There are simply no more b o ttle s of beer
on the w a ll.\ n ");

.
, .

//

//
//

v //

J BeerSony.l
jJgProduos I

//
//

Created b Aaron Hillegass on 9/1/11.


Copyright () 2013 8ig Nerd ftanch, A ll rig h ts reserved.

#include <stdio.h>
void singTheSong(int numberOfBottles)

i f (numberOfBottles * * ) {
printf("There are simply no more b o ttle * of beer on the w all, \n*')j
} else {
printf(*'%d bottles of beer on the wall* %d bottles of b e e r.W ,
number0f8ottles, numberOfBottles);
int oneFewer * numberOfBottles * X;
printf(**Take one down, pas i t around, %d bottles of beer on the w all.\n'
oneFewer);
singTheSong(oneFewer); / / This function c alls it s e lf !
p rin tf(*P u t a bottle in the recylcing, %d empty bottles in the bin. \nM,
numberOfBottles);

. 5.6.

, .
,
. .
, ,
.

51

,
. 5 ,
. ,
(
).
.
,
, ,
oneFewer. , ,
m ain().
,
. singTheSong.
SjBeetfong- miln.c

Running tMiSong

'
ffwllngTOcSong|
7 0 slngTheSono
p | 71 .ttogTheSong
5 72 singTheSong
73 stngTheSong

074lM^hrtOflQ
QTtMfTWSong
7S singTheSong

P |7 7 singTheSong
s*ngTheSong

07ttMgTtaSeng
$ 5 *0 singTheSong
f 5 * l singTheSong
Q ttiM fT ta S o n g
Q u stngTheSong
f|M

singTheSong

Q M sk>gTheSong
fS 16 stngTheSong
0 * 7 stngTheSong
f|e a s in g T h *S o n g
f |M

singTheSong

f|e O **ngThtSong
f l l l tmgThe5ong
2 se>gTheSeng
ffn

v*ngTheSong

j^9 4u ngT H e5ong


f f t S singTheSong
f |N

sMgTheSong

*7|
*tn g T h rto n g

; v o i d singTheSong(int numberOfBottles)
{.
i f (num berO f8ottles = 0 ) {
prirvtf('*Therc a re simply more b o ttle s of beer on the w a\l.\n 1*);
} e ls e {
p rin tf("% d b o ttle s of beer on the w all, %d b o ttle s of b e e r.\n '\
numberOfBottles, numberOfBottles);
in t oneFewer numberOfBottles - 1;
p rin tf(" T a k e one down, pass i t around, %d b o ttle s of beer on the w all.\n ",
oneFewer);
singThe5ong(oneFewer); / / This function c a lls i t s e l f l ^ Threadi:Stoppe^bre~.
p rin tf(* 'P u t a b o tt le in th e recy clin g , %d empty b o ttle s in the b in .\n ",
numbe rO fB o ttles);


Locel

w^^^^^^^^v^^^^^wvi^Wv^w^^^^w^^wA

Q n u m berO fB o tttes - (In ti 99


oneFew er - (nt) 98

;jm

^ . ^ ^ ^ ',

:Tflke one down, p3ss i t er

wall.
:4 bottles of beer on the well. 4 bottles of beer.
!Take one down, pass it aroond, 3 bottles of beer on
!wall.
!3 bottles of beer on the wall. 3 bottles of beer.
!Take one down, pass it around, 2 bottles of beer on
;wall.
:2 bottles of beer on the well* 2 bottles of beer.
Take one down, pass it around, 1 bottles of beer on
wall.
! 1 bottles of beer on the wall. 1 bottles of beer.
Take one down, pass lt around, 8 bottles of beer on
wall.
!Current languages auto} currently minieal

the
the
the
the

. 5.7.


. , ,
. ( , |
, , .)
Ila : , .

52

,
.
,

. .
, i^
, .
,
, .

, , ,
, .

return
.
, , . (
, void.)
Degrees.
main.c main() ,
. main().
#include < std io .h >
float fahrenheitFromCelsius(float cel)

{
flo a t fahr - cel * 1.8 + 32.0;
printf("%f Celsius is Xf Fahrenheit\n", c e l, fahr);
return fahr;

in t m ain (in t arg c , const char * a r g v [])

{
float freezeInC = 0;
float freezeInF s= fahrenheitFromCelsius(freezeInC);
prlntf("Water freezes at Xf degrees Fahrenheit\n", freezeInF);
return 0;

, fahrenheitFrowCelsius()
freezeInF f l o a t ? , ?

return

53


return. , :
f lo a t a v e ra g e (flo a t a , f l o a t b)

{
return ( + b )/ 2 .0 ;
p rin tf(" T h e mean j u s t i f i e s the end\n");

, p r i n t f ( ) .
: 0
main()? 0, :
. - - ,
1.
0 1 if; 1
true, 0 f a ls e ,
1 , 0 . ,
main () . 0 !
.
,
EXIT_SUCCESS EXIT_FAILURE,
0 1 .
stdlib.h:
#include <stdio.h>
#include < std lib .h >
f lo a t fa h re n h e itF ro m C e ls iu s ( flo a t c e l)

{
f lo a t fa h r = c e l * 1 .8 + 32.0;
p rintf("% f C e ls iu s i s %f Fah ren h eit\n ", c e l, fa h r);
return fa h r ;

>
in t m ain(int arg c, const char * a rg v[])

{
f lo a t freezeInC = 0;
f lo a t freezeInF * fa h ren h eitFro m C elsiu s(freezeIn C );
p rin tf("W a ter fre e z e s at Xf degrees Fahrenheit\n", freezeInF);
return EXIT SUCCESS;

>

.-..-;.,-/,;r.-'w off-W |H

0 EXIT_SUCCESS.

54


,
. ,
. .
, -
, la stT e m p e ra tu re .
:
#include <stdio.h>

# in c lu d e < s td lib .h >


//

flo a t lastTemperature;
flo a t fa h re n h e itF ro m C e lsiu s(flo a t c e l)

>

lastTemperature = cel;

- ' . ' 3

f lo a t fa h r = c e l * 1.8 + 32.0;
p r in t f("%f C e ls iu s i s %f Fahrenheit\n", c e l, fa h r);
return fa h r;

in t m ain(int arg c, const char * a rg v[])

f lo a t freezeInC = 0;
f lo a t freezeInF = fa h ren h eitFro m C elsiu s(freezeIn C );
p rin tf("W a te r fre e z e s a t %f degrees Fahrenheit\n", freezeInF);

p rin tf("T h e la s t temperature converted was %f\n", lastTemperature);


return EXIT_SUCCESS;

,
.
. , . ,
.
. ,
, - -
,
u
, ,
- ,
4 ?

55

,
main.c,
.
/ /
sta tic flo a t lastTemperature;

,
:
/ / lastTemperature 50
sta tic flo a t lastTemperature = 50.0;

,
.
. III,
Objective-, ,
.

180 .
Triangle.
main.c ,
. :
#include <stdio.h>
/ / Add your new function h ere
int main(int argc, const char * a rg v [])

{
flo a t angleA 30.0;
flo a t angleB 60.0;
flo a t angleC * remainingAngle(angleA, angleB);
printf("The th ird angle is % .2f\n", angleC);
return 0;

. ,"~^^^^^^^^^^^^^

The third angle is 90.00

, . ,
. :
( ).
,
.

printf()

, p rin tf( ) ,
. p r i n t f ( )
, . , .
C la s s C e r t if ic a t e s main.c
congratulateStudent().

void c o n g ra tu la te S tu d e n t(c h a r * s tu d e n t, c h a r * c o u rse , i n t numDays)


{

p rin tf("% s has done as much %s Programming as I could f i t


in to %d d a y s .\n " ,
stu d e n t, c o u rse , numDays);

>

\J

prin tf()? -
, . , .
printf() .
( , ), *
.

57

, p r i n t f ( ) , .
.
: %s, %s %d.
, ,
stu d e n t, c o u rse numDays. :
.
student co u rse , :
Cocoa has done as much Mark Programming as I could f i t in to 5 days.


. %s , ,
%d . (
, .)
: s t u d e n t c o u rs e
char *. , c h a r * .
Objective-C 14, c h a r * 34.
, \n ? p r i n t f ( )
,
. \n (
).
.


.
, . (,
) .
(, ) .

.
(), ;
, .
8-, 16-, 32- 64-.
, , .
, .
&* 0
255. ? 2 * 256 ,
0.

58

64-
9 223 372 036 854 775 808 9 223 372 036 854 775 807. p | ?
, , . 263= 9 223 372 036 854 775 80ft
,
:
UInt32 x; / / 32-
S In tl6 ; / / 1-

, ,
3.
char ;
short bj
in t ;
long d;
long long e;

//
//
//
//
//

8-
16- (
)
32- ( -
)
32- 64- ( )
64-

char ?
8- ,
char, short, in t, long long long , unsigned .
, . (

.) 32-, 64-. (
8).
Apple , 32-
32- 64- 64- :
NSInteger g;
NSUInteger h;

Apple.
long unsigned long.


Numbers.
t0 (
) p rin tf();
include <stdio.h>
Int u i n (in t argc, const char * argv[J)

59

{
in t x = 255;
p rin tf(" x is % d.\n", x );

return 0;

>
:
x is 255.

, %d
. ?
.
:
#include < stdio.h>
in t main ( in t arg c, co n st char * a rg v [])

{
i n t x = 255;
p rin tf(" x i s % d.\n", x );
printf(''In octal, x is %o.\n", x);
printf("In hexadecimal, x is %x.\n", x);

re tu rn 0;

}
. :
x is 255.

In o ctal, x is 377.
In hexadecimal, x i s f f .

( 33.)
( ,
)? % 1
( long) 11 ( long long). ,
i n t long:
#include <stdio.h>
int main (int argc, const char * argv[])

{
long x - 255;
printf("x is %ld.\n", x);
printf("In o ctal, x is %lo.\n", x);
printf(*'In hexadecimal, x is %lx.\n", x);

return 0;

>

60

&*
#include <stdio.h>
in t main ( in t argc, const char * argv[])

unsigned long x = 255;


p rin tf( " x i s %lu.\n", x ) ;
// ,
//
p rin tf( " I n o c t a l, x i s %lo.\n", x);
p rin tf( " I n hexadecimal, x i s %lx.\n", x);
return 0;

+, - * , .
,
: * + -. main.c
^ :
#include <stdio.h>
in t main ( in t argc, const char * argv [])
{
p r in tf(" 3 * 3 + 5 * 2 = %d\n", 3 * 3 + 5 * 2 );

return 0;

}
:
3 * 3 + 5 * 2 = 19

'
J


,
. :
#include <stdio.h>
in t main ( i n t argc, const char * a r g v [ ] )

printf("3 * 3 + 5 * 2 - %d\n", 3 * 3 + 5 * 2 );
p r in t f ( " ll / 3 - %d\n", 11 / 3 )j

61

re tu rn

0;

>
11 / 3 = 3.666667, ? .
11 / 3 3.
. (
, -11 / 3 -3). ,
: 11 3 3
2. . %
/, :
#include <stdio.h>
in t main ( in t argc, const char * arg v [])

p rin tf(" 3 * 3 + 5 * 2 = %d\n", 3 * 3 + 5 * 2);


p rin tf(''ll / 3 = %d remainder of %d \n", 11 / 3,

11 %3);

return ;
}

...............................

;;

3.666667 3? in t
float .
, .
flo a t :
in t main ( in t arg c, const char * a rg v [])
{

* :

p rin tf(''3 * 3 + 5 * 2 = %d\n", 3 * 3 + 5* 2);


p r i n t f ( " l l / 3 = %d rem ainder o f %d \n " , 11 / 3,
p rin tf( " ll / 3.0 = %f\n", 11 / (float)3);

11 %3);

retu rn 0;
>

""''^ v r

'


, 3.666667. : /
,
. ,
.


, ,
. , x 1,
+ x:

62

in t x = 5;
x * x + 1; / / x 6

, >
,
. , x 1
(++):
in t x = 5;
x++; // x 6

( - - ) ,
1:
int x = 5;
x--j // x 4

x 1, 5? ,
:
int x = 5;
x = x + 5; // x 10

:
int x = 5;
x += 5; // x is 10

x +5.
+= -=, *=, /= %=.
( )
abs ( ) .
long, lab s().
stdlib.h:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, const char * argv[])

{
printf("3 * 3 + 5 * 2 = %d\n", 3 * 3 + 5 * 2);
p r in t f ( " ll / 3 * %d remainder of %d \n", 11 / 3, 11 %3);
p r in t f( ''ll / 3.0 * %f\n\ 11 / (flo a t)3 );
printf("The absolute value of -5 i s %d\n", a b s ( - 5 ) ) ;
return 0;

"

"

63


(, 3.2)
( ).
, 10
. , 345.32
3.4532 x 102. , : 32-
8 (
), 23 ;
.
/
, , .
, :
flo at g;
/ / 32-
double h;
// 64-
long double i; // 128-


p r i n t f ( ) ,
%f %e.
main.c:
int main (int argc, const char * argv[])

{
double = 12345.6789;
p rintf("y is %f\n", );
p rin tf("y is %e\n", );
return 0;

>

^ H 9 if* 6 C { n V

. :
is 12345.678900
iS 1 , 234568e+04

, Xf
, %e .
: %f 6
, .
, :

64

i n t main ( i n t a rg c, c o n s t char

a rg v [])

double = 1234 5.67 89 ;


p r i n t f ( " y i s % .2 f\n " , ) ;
p r i n t f ( " y i s % .2e\n", ) ;
retu rn 0;

}
:
i s 1 2 3 4 5 .6 8
i s 1 .2 3 e + 0 4


+, -, * / , ;
. , .
, Mac manmath
:
, , ..
-
,
:
#include <math.h>
: ,
!

! main.c ,
1 .
(: 0.841).

Xcode Coolness.
, ,
( 10 ). :
#include <stdio.h>
in t m ain(int argc, const char * arg v [])
{
printf("Aaron i s Cool\n");

retu rn 0;
>
.
,
10- , , .
?
:
#include <stdio.h>
in t m ain(int arg c, const char * a rg v [])
{
printf("Aaron
printf("Aaron
printf("Aaron
printf("Aaron
printf("Aaron
printf("Aaron
printf('*Aaron
printf("Aaron
printf("Aaron

is
is
is
is
is
is
is
is

Cool\n");
Cool\n");
Cool\n");
Cool\n");
Cool\n");
Cool\n");
Cool\n");

ls

Cool\n*');

C o o l\n ");

&

66

printf("A aron i s Cool\n");


printf("A aron i s Cool\n");
printf("A aron i s C ool\n");
re tu rn 0;

>
.

while

w hile. while
i f , 4:
,
i f
. w h ile ,
f a l s e .

. 7.1. while
m a in () :
#include < stdio.h>
i n t m ain (in t arg c, const char * a rg v [])
{
In t 1 0;
while (1 < 12) {

prin tf("% d . Aaron i s C o o l\n " , i ) ;


i++ j

>

return 0;

>
.
( i < 12) .
,
.
i .
:
, . . 7.1
- while.

for
w hile ,
:

while ( ) {

:
for. f o r :
for (; ; ) {
;

}
, for:
#include <stdio.h>
int main(int argc, const char * argv[])

{
for (int i 0; i < 12; i++) {
printf("%d. Aaron is Cool\n", i) ;

>
return 0;
>

68

. 7.2. for

,
.
, . ,
,
.
.
, 15.

break
. ,
x,
x + 90 = x2. :
0 11
. :
#include <stdio.h>
int main(int argc, const char * argv[])

{
in t i;
for ( i * 0; i < 12; i++) {
prlntf("Checking i %d\n", i) ;
i f (i + 90 i * i) {
break;

continue

69

p rin tf("T h e answer i s %d.\n", i ) ;


return 0;

>
. :
Checking i
Checking i
Checking i
Checking i
Checking i
Checking i
Checking i
Checking i
Checking i
Checking i
Checking i
The answer

=0
= 1
= 2
= 3
=4
= 5
= 6
= 7
= 8
= 9
= 10
i s 10.

, break .

. 7.3. break

continue
:
, , .

continue. , ,
4'io , 3, .
?

70

#include <stdio.h>

/ i n t argc, const char * a rg v [ ] )


i n t m ain(int arg >
{

g i<if i( i -.%I3 ==
;
i ++) {
0) 1
continue;

J r in tf (" C h e c k in g i = * d \n " , i ) i
if (i +

90

-- i

1> {

break;
>

p r i n t f ( " T h e answer i s % d .\n ", i ) ;


r e t u r n 0;
>

:
Checking i
Checking i
Checking i
Checking i
Checking i
Checking i
Checking i
The answer

= 1
= 2
= 4
= 5
= 7
= 8
= 10
is 10*

. 7.4. continue

do-whHe

71

do-while
do-w hile,
. do - w hile ,
. , .
,
do-while, :
in t main(int argc, const char * argv[])

i n t i = 0;
do {
printf("% d. Aaron i s Cool\n", i ) ;
i++j
} while ( i < 13);
return 0;

}
;. , ,
, d o -w h ile
:
do { - } while ( );

- do-w hile:

. 7.5. do-while

71 7

H tn m iN tr nporpMiwv. i 99 joO
"wpr* 3 T t* y w rr 5. nporpaai
Foufxi ? npr>rpWtfMM .

99

fi

9i
* 1
t?
*OuHd **'

Qrwp<n*

0 rr*

**rrfC* <
pCtNMrt |
U&tMMk *

, ,
. , 1 .
1 , 0
.
.
,
. ,
,
,
.
1

0
| ----------------------------------------------------------- ----- 1

t~~"
0

-----

--,

8.1.

.
). 32- 64- ,
, . 64- ,
, 2*.

74


Xcode : Ad
dresses.
,
.
&:
#include <stdio.h>
int main(int argc, const char * argv[])

{
in t i = 17;
p rin tf(" i stores it s value at %p\n", &i);
return 0;

}
%p
. .
:
i stores it s value at 0xbffff738

, i
. .
, ,
, , .
:
int main(int argc, const char * argv[])

int i p 17;
p rin tf("i stores its value at %p\n", &i);
printf("this function starts at %p\n", main);
return 0;

>
.


? , eot.^
31**

75

,
. ,
p tr , float,
:
f l o a t * p tr;

, ptr
float. float; ,
flo a t.
addressOfI,
int. i.
in t m a in (in t a rg c , co n st char * arg v [])
{
i n t i I 17;
i n t *addressO fI = &i;
p r i n t f ( " i s to r e s i t s v alu e a t %p\n", addressO fI);
p r i n t f ( " t h i s fu n c tio n s t a r t s a t %p\n", main);
re tu rn 0;
>

.
.
. ,
, . ,
, , .
,
. :
, , ,
.
.


, *.
, addressofI:
Int maln(int argC/ const char * arg v [])

<

Int

i 17;
int *addr*ssOfl

&i;

&

76

p r in t f ( " i sto re s i t s value a t %p\n", addressO fI);


p r in tf ( " th is function s t a r t s a t %p\n", main);
p rin tf("th e in t stored at addressOfI i s %d\n , *addressO fI);
retu rn 0;
>
: (*)
. -, a d d r e s s O fI i n t *.
, ,
i n t .
-, in t , , a d d re s s O fI.
,
(dereferencing) .
*
:

int main(int argc, const char * argy[])


{

int i = 17;
int *addressOfI = &i;
p rin tf(" i stores i t s value at %p\n", addressOfI);
*addressOfI = 89;
printf("Now i i s %d\n", i ) ;

return 0;
}
.
, ,
. , .
*
m a in (),

addressOfI = 89;
X code
ro ' i n t ' ' i n t * '.
.


, , , '^,
, . ,
?

NULL

77

siz e o f().
:
in t m ain(int a rg c, const char * argv[])

{
in t i - 17;
in t *addressOfI = & i;
p r i n t f ( " i sto re s i t s value at %p\n", addressOfI);
*addressOfI = 89;
printf("Now i i s %d\n", i ) ;
p rin tf(" A n in t i s %zu bytes\n", s iz e o f( in t ) ) ;
p r in t f ( " A p o in te r i s %zu bytes\n", s iz e o f( in t *));
return 0;

p r in t f ( ) %zu. sizeo f()


s iz e _ t,
%zu.
. 4 ,
32- .
8 , 64- .
s i z e o f ( ) ,
:
in t m ain(int argc, const char * argv[])

{
in t i = 17;
in t *addressOfI = & i;
p r in t f ( ''i stores i t s value at %p\n", addressOfI);
*addressOfI = 89;
printf("Now i is %d\n", i ) ;
p rin tf("A n in t i s %zu bytes\n", s iz e o f( i) ) ;
p rin tf(" A poin ter is %zu bytes\n", sizeof(addressOfI));
return 0;

>

NULL

, ,
,
. NULL:

78

float *yPointer;
/ / myPointer NULL,
/ / .
*yPointer * NULL;

NULL? ,
.
NULL . 1 :
flo a t *wyPointer;

p 8
// *yPointer ?
I f (yPointer) {
// *yPointer NULL
... , m y P o in te r...

} >bc {
// wyPointer NULL

, , NULL
n l l . , O bjective-C n i l ,
.


flo a t :
f lo a t *powerPtr;
f lo a t* , *
:
flo a t* pow*rPtr;
1$ , J*J|>HK
1| | < w tf^
<
?
( iu*prMfiiHUi , |^
i,

, , t j
float
.tybuurtr, *

fU w t

flM t* k< c{

79

! b flo at,
P f l o a t . , ,
* :
f lo a t *b, *c;
* ,
.

, ,
f l o a t .
Mac s h o r t 2- ,
.
? ? unsigned
short .
?

i J

m odf(), double
. , 3,14
3, 0,14.
m odf(), .
. modf()
?
modf() ,
. ,
. PBR.
main.c:
#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[])

{
double p i * 3.14;
double in teg erP art;
double fra c tio n P a rt;
/ / integerP art
fra c tio n P a rt modf(pi, & in te g e rP a rt);
/ / , in teg erP art
p rin tf(" in te g e rP a rt %,0f, fra c tio n P a rt * X.2f\n", integer
fra c tio n P a rt);
return 0;

>

no

81

.
, (),
.

, . :
.
.
, .
.
modf() . ,
, ,
.
, .




: . {x,y)
.
(theta, radius) theta
radius .
, ,
.
.

. 9.2.

:
void c a rte s ia n T o P o la r(flo a t x, f l o a t , f l o a t * rP tr, f lo a t *thetaPtr)

, x . ,
,
ra d iu s th e ta .
main.c
main():
#include <stdio.h>
#include <math.h>
void cartesianToP olar(float x, f lo a t , double *rPtr, double *thetaPtr)

{
/ /
*rPtr = sqrt(x * x + * );
// theta
flo a t theta;
i f (x *= 0.0) {
i f ( *= 0.0) {
theta 0.0;
//
) else i f ( > 0) {
theta * M_PI_2;
> else {
theta * - M PI 2;

>
} else {

83

th a ta a ta n (y /x );

>

/ / theta no
th e ta P tr * th e ta ;

in t * a in ( in t argc> const char * argv[])


{
double p i * 3.14;
double in te g e rP a rt;
double fr a c t io n P a r t ;
// in te g e rP a rt
fr a c tio n P a r t * m odf(pi, & integerPart);
// , integerPart
p r in t f ( " in t e g e r P a r t = %.0f, fra ctio n P a rt = %.2f\n", integerPart,
fr a c t io n P a r t ) ;
double x & 3 .0 ;
double 4 .0 ;
double radius;
double angle;
ca rte sia n T o P o la r(x , , &radius, &angle);
p rin tf(* * (X .2 f, X .2 f) becomes (%.2f radians, %.2f)\n", x, , radius,
angle);
retu rn 0;

'g H ' ,

t ,g

Pnc. t . l . c*testanTbPoH)

84

NULL
,
.
, ?
NULL, :
.
, ^
, NULL. cartesianToPo
la r ( ) :
void cartesianToPolar(float x, flo a t ,
*thetaPtr)

double *rPtr, double

{
/ / rPtr NULL?
i f (rP tr) {
/ / no
*rP tr * sqrt(x * x + * );
>
/ / thetaPtr NULL?
i f (!th e ta P tr) {
/ /
return;
>
/ / theta
flo a t theta;
i f (x * 0.0 ) {
i f ( * 0.0 ) {
theta 0.0;
/ /
> else i f ( > 0) {
theta * M_PI_2;

> else {
theta - H_PI_2;

>
> tb * {
#

K*K
*bix
*Ho


. ,
. ( ,
? , .
20 , ,
30 .
, .)
f l o a t ,
, in t, .
Person.
Person : h eig h tIn Meters f l o a t w eightInK ilos in t.
: BMICalc.
main.c ,
:
#include <stdio.h>
// Person
struct Person {
float heightInMeters;
int weightInKilos;

int main(int argc, const char * a rg v [])

struct Person person;


person .weightXnKilos 96;

p rin tf( "person"weighs Xi kilogre*s\n", person.*eightInK ilos);


#

86

10

printf("person is %.2f meters ta ll\ n " , person.helghtInMeters);


return 0;

}
-
.
. 10.1 , m ain()
.
mafnQ

struct Person
weightfnKilos = 96
heightlnMeters 1.8

p e rs o n

. 10.1.

,
, typ ed ef
,
main.c,
ty p e d e f Person:
#include <stdio.h>
/ / Person
typedef struct {
flo at heightlnMeters;
in t weightXnKilos;
} Person;
in t main(int argc, const char * argv[])

Ptrson

^ ^^

^^

person;
person. weightXnKilos * 96;
person.heigfrtInMeters 1.8;
printf("person weighs XI k ilo g ra a s\ n ", person.w eightInK ilos);
printf("person is X .2 f aeters t a ll\ n " , person.heightInM eters);
return 0;

I| ^

&

typedef. *
Per*son 1* ***
b o d y H iiiI n tf tx ( ) , P e r s o n apr>*
. / ^ i i i l n ( );

87

include <stdio.h>
// Person
typedef s tru c t {
flo a t heightInMeters;
in t w eightInK ilos;
} Person;
flo a t bodyM assIndex(Person p)

{
return p .w eig h tIn K ilo s / ( p . heightInMeters * p.heightInM eters);

>
in t m ain(int arg c, const char * a rg v[])

{
Person person;
p erson .w eig h tIn K ilo s 96;
p e rs o n . h e ig h tIn M e te rs * 1 .8 ;
f lo a t fami bodyMassIndex(person);
p rin tf( " p e rs o n has a BMI o f X .2 f\ n " , bm i);

return 0;
>

, ,
ta.
tta . :
stru ct ta (
in t
t* _ s e c ;
In t
ta _ * ln ;
in t
t* _ h o u rJ
in t
te *d a y ;
In t
ta_aon;
in t
t*_ y *e r;
In t
t> w d ly;
in t
t* jfd iy ;
in t
ty *_ |fd s t;

ch#r

t*U PtO f#*


* lO_ / fjt\t;

/
/*
/
f/

[ 0 - 60 ] * /
[ 8 *S9 ] * /
{ 8 - B ] * /
*onth ( 1 - 31) /

/ l # - U ) /
/ 1908 * /
/ ^ { 8 - 8 }
/ 1 [ 0 -) 6 S] /
% * /
## 8 * * /
/# (0 1 nonci * /

10

tlm e() 1970


. lo ca ltim e _ r( ) ^.
py tfli (, adpeQ
1970 t * ) . , *
t a :
long secondsSincel970 tiw e(N U lL);
'* * ''
4 |
p rin tf(" It has been Xld seconds since 1970\n", secondsSincel970)*

' ^

|x V

stru ct ta now;
Iocaltiffie_r(&secondsSincel970, &now);
p rin tf("T h e time is %d:%d:%d\n", now.tm_hour, now.tm_min,
now.tm_sec);

, , ( -) 4 .
(: tm_mon = 0 , *
1. <tim e. h> .)

<

i^^^^^^^^^^i2^CiuJi=^U=^-====.'===;,^_=_.==i=__^__^i^Liui^^2^^=^-=,=i^^feMiiiB^

,
.
. ( -
.)

. ,
,
, .
, ,
.
.
(, , ,

Youtube.)
m a llo c ().
, (heap),
. , f r e e ( )
. ,
, 1000 f l o a t .
#include <stdio.h>
#include <stdlib.h> / / malloc free std lib
int main(int argc, const char * argv[])
{
//
float *startOfBuffer;
/ /

&

90

11

startOfBuffer = malloc(1000 * s iz e o f ( f lo a t ) ) ;
//

. . . .. .

/ /

fre e (s ta rtO fB u ffe r);


//

startO fB uffer = NULL;


return 0;

>
sta rtO fB u ffe r
.

. 11.1. , ,
,

.
,
.
malloc ()
. ,
Person, :
#include <stdio .h >
in c lu d e < s td llb .h >
typedef s tru c t {
f l o a t heightInM eters;
In t w eig htIn K ilo s;

} Person;

91

f l o a t bodyM assIndex(P erson * p )

{r e tu r n
>

p - > w e ig h t I n K ilo s /

( p - > h e ig h tIn M e te r s * p -> h e ig h tIn M e te rs );

i n t m a in ( in t a rg c , c o n s t c h a r * a r g v [ ] )

/ / Person
Person * x - (P e rs o n * ) m a llo c ( s iz e o f ( P e r s o n ) ) ;
/ /
x - > w e ig h t I n K ilo s = 8 1 ;
x - > h e ig h tIn M e te r s = 2 . 0 ;
/ /
f l o a t xBMI = b o d y M a s s In d e x (x ) ;
p r i n t f ( " x has a BMI o f = % f \ n " , x B M I);
/ /
fr e e ( x );
//

x = NULL;

re tu rn 0 ;

- >. p->weightInKilos :
p weightInKilos>.

. , Objective-C.
.

Objective- Foundation
, , ,

, Objective-.
,
.
Objective- Foundation
, . ?
...

.
, , .
,
. , ,
, ,
.
1980-
.
.
Objective-C.
.
, ,
. Objective-C
,
.
.
,
.
.
.
, iPhone ,
CLLocation. CLLocation
CLLocation. CLLocation
: ,
. . ,
CLLocation,
CLLocation.

95


Objective-C.
(Command Line Tool),
Foundation (. 12.1). TimeAfterTime.
Chooteoptionsforyo*irniwproject

- - -------- ----

II .-I II-------- ----------------- ----------------------------------------------------------------------------------------------- ;

. 12.1. Foundation

Objective-C .m.
main.m, :
#import <Foundation/Foundation.h>
int main (in t argc, const char * argv[])

autoreleasepool {
NSDate *now = [NSDate d a te ]j
NSLog(g"The new date liv e s at %p", now);

}
>

return

!
date NSDate. date NSDate
NSDate, /
, .

now. * ^
NSOate.
NSLog() Objective-C, p rin tf(); yt$w^
^ , % <*
. |^
\n.
. ^
2011-08-05 11:53:54.366 T im eA fterT im e [4862:707] The new date liv*t at
0x100114dc0
p rin tf() NSLog() ^
, , .
, NSLog(),
.
NSLog() %p . ^
, %@,
:
#import <Foundation/Foundatlon. h>
int main (in t argc, const char * argv[])

0 autoreleasepool

{
NSOate *now = [NSDate date];

NSLog(0"The date is %Q", now);

>

return

:
The date is 2011-08-05 16:09:14

+0000



:
, ;
.
( ) W
.

97

NSDate . NSDate
( ) /, -
, 0:00 ( ) 1 1970 .
, tim eIntervalS incel970
NSDate, now.
#im port < F o u n d a tio n /F o u n d a tio n .h >
i n t main ( i n t a rg c , c o n s t c h a r * a r g v [ ] )

@ a u to re le a se p oo l {
NSDate *now & [NSDate d a t e ] ;
NSLog(0"The d a te i s %@" now );

double seconds = [now tim eIntervalSincel970];


NSLog(#"It has been %f seconds since the s ta rt of 1970.",
seconds);

>

return 0;

, d a te
100 000 .
d a te , d a te .
: .
d a te m ain():
#import <Foundation/Foundation.h>
in t main ( in t argc, const char * arg v [])

0autoreleasepool {
NSDate *now = [NSDate d a te ];
NSLog(@"The d ate is %@, now);
double seconds [now tim eIn terv alS in cel970];
N5Log(0"It has been %f seconds sin ce the s t a r t of 1970.",
seconds);
NSDate * la te r [now dateByAddingTlmeInterval:100000];
NSlog(#"In 100,000 seconds i t w ill be %@", la te r);

>

If

return 0;

98

12

[now d ateB y A d d in g T im eIn terv al* ia


now , ( > ^<
d ateB y A d d in g T im eIn terv al eo a( ce e o p );

100 000 .
: ,

[now dateByAddingTimeInterval:iO 0Q0Qj


:

. 12.2.


. 12.3 .
NSDate . now l a t e r ^
main(). NSDate ( )

main()

now = D
later =

. 12.3. TimeAfterTime
^_

11< : NSDate, iOS Mac 0S^


.
.

99

id
,
:
NSDate * e x p ira tio n ;

, ,
. id,
- O bjective-.
id:
id d eleg a te ;

(* )
id .
, ,
. ,
.
,
.

NSDate
. : d a te ,
. . :
NSDateComponents *comps = [[NSDateComponents a l l o c ] i n i t ] ;
[comps setY ear:1 9 6 9 ];
[comps setM onth:4];
[comps setD ay:30];
[comps setH o u r:1 3 ];
[comps setM in u te:1 0 J;
[comps se tS e c o n d :0 ];
NSCalendar *g = [[N SCalendar a l l o c ]
in itW ith C a le n d a rId e n tifie r:N S G re g o ria n C a le n d a r];
NSDate *dateOfBirth * [g dateFromComponents: comps];

NSDate tim e In te rv a lS in c e D a te :
double d [laterDate tim e I n t e r v a l S in c e D a t e : e a r l ie r D a t e J ;


1
*

Mei

!
NSDi

12 .


M
u ^H
^|
N S D a te

NSD

*now = [NSDate d a t e ] ; i

date . ,
NSDate. date '
NSDate.
double seconds = [now timeIntervalSincel970];

timeIntervalSincel970 .
, M
erc*
timeIntervalSincel970 double.
NSDate *later = [now dateByAddingTimeInterval:100000];

dateByAddingTimeInterval:
,
NSDate.


alloc ,
. ,
init. alloc in it
Objective-C. #
flr
:
[[NSDate alloc] in it 3>

CJ


#ini
in t

101

,
. , NSDate
a llo c , ( )
i n i t .
i n i t (
, a llo c ),
i n i t . ,

NSDate *now = [NSDate d a te ] ;

NSDate *now = [[NSDate a llo c ] i n i t ] ;


. , NSDate
, .
NSCalendar. NSCalendar,
, . NSCalendar
main.m:
#import <Foundation/Foundation.h>
in t main ( i n t a rg c , c o n st ch ar * a rg v [])

@ autoreleasepool {
NSDate *now = [[NSDate a llo c ] i n i t ] ;
NSLog(0"The d a te i s %@", now);
double seconds * [now tim e In te rv a lS in c e l9 7 0 ];
NSLog(0"It has been %f seconds sin c e th e s t a r t o f 1970."*
seconds);
NSDate * la te r - [now dateByAddingTimeIrtterval:100000];
NSlog(#"In 100,000 seconds i t w ill be %@", l a t e r ) ;
NSCalendar *c a l [NSCalendar cu rren tC alen d ar];
MSUInteger day [c a l ordinalityOfUnit:NSDayCalendarUnit

in U n it:NSMonthCalendarUnit
fo rD ate: now];

102

13

NSLog(0"This is day %lu of the month", day);

>

return

>
Coo6ujeHHeHa3bmaeTCHordinalityOfUnit:inUnit:forDate: ^

. .
.
. I
Objective-C , 1
. ( Xcode f
, ,
. ,
Xcode.)
NSDayCalendarUnit
NSMonthCalendarUnit. NSCalendar.
, .
, .
,
:
,
i**<^# *
NSUInteger hour = [cal ordinalityOfUnit:NSHourCalendarUnit
inUnit:NSYearCalendarUnit
forDate:nowJ;
|

y^

ei

(%

nil
- n i l
, . Objective-C n il
( NULL 8).
- ni
s
. n^PKTV ,
v

_ ,.^


nil.
:
i f (fido I- n il) {
[fido goGetTheNewspaperJ;

>

103

Objective-C , n il
; . ,
:
Dog *fido = n il;
[fido goGetTheNewspaper];

1: ,
, ,
n il.
2: n il,

.
Dog *fido = n il;
Newspaper *d a ily * [fid o goGetTheNewspaper];

d a ily . ( ,
,
nil . ,
.)

Mac NSTimeZone.
systemTimeZone,
( NSTimeZone), isDaylightSavirigTiroe, YES,
.
Foundation, ,
.

14

NSString

NSStrlng -- , NSDate. NSStrto|


.
N SString
NSStrlng *lament @"Why m el?";

, TimeAfterTime :
NSLog(0"The date ls %@, now);

NSLog() ~* Objective-C ( I), print^()^


NSLog()
NSStrlng.
NSStrlng
strlngW lth F o rm at::
NSString *x [NSStrlng
stringW lthForm at:0"The best

number ls %d"* S]i

length:
NSUInteger charCount [x le n g th ];

ls E q u a l: :
i f ([lam ent ls E q u a l:x ])

N5Log(@"%@ and %@ are equal> lament* x );

.
C.*
char *lament "Why mel?";
char *x;
asprlntf(& x, "The best number is %d", 5)j

105

s lz e _ t charCount = s t r l e n ( x ) ;
l f (s trc m p (la m e n t, x ) == 0)
p r in tf( " % s and %s a re e q u a l\n " , la m en t, x ) ;
fre e (x );

|v 34. , ,
NSString . NSString ,
. , NSString (
)
. ? .
? .

NSHost .
NSHost NSHost currentHost.
NSHost:

+ (NSHost *)currentHost


NSHost localizedName, eKTNSString:

- (NSString *)localizedName

Foundation, *
. ( .)

NSArray

NSArray, NSString, Objective-C


NSArray ,
, NSDate,
.
: Foundation
DateList. main.m main( ):
in t main(int argc, const char * arg v [])

0autoreleasepool {
/ / NSDate
NSDate *now = [NSDate d a te ];
NSDate *tomorrow =
[now dateByAddingTimeInterval:24.0 * 60.0 * 60.0];
NSDate *yesterday *
[now dateByAddingTimeInterval:-24.0 * 60.0 * 60.0];

/ / *
/ / (n il - )
% NSArray *dateList = [NSArray arrayW ithObjects:now, tomorrow,
yesterday, n iI];
/ / ?
NSLog(0"There are %lu dates, [dateList count]);

/ /
NSLog(@ The
NSLog(@"The

f ir s t date is %@", [dateList objectAtIndex:0]);


third date is %@", [dateList objectAtIndex:2])j

NSArray

>

107

re tu rn 0 ;

NSArray , ,
:
I count: ;
objectA tIndex: , ,
| .
,
. :
0, 1 . . , count
, 100 , objectAtIndex: 0 99.
. 15.1 . :
NSArray NSDate.

. 15.1. DateList


for. main.m:
#import <Foundation/Foundation.h>
int main(int argc, const char * arg v [])

0autoreleasepool {
/ / NSDate
NSDate *now * [NSDate date];

108

15 NSArray

NSDate *tom orrow * [now d a te B y A d d in g T im e In te rv a l:2 4 0 % ^


* 6 0 .0 ] ;
61
NSOate * y e s te r d a y * [now d a t e B y A d d in g T im e I n te r v a l:- 2 4 . 0 *
6 0 .0 ] ;
/ / *
/ / ( n i l - )
NSArray * d a t e L is t = [N S A rray a rra y W ith O b je c ts :n o w , tomorrow
y e s te rd a y , n i l ] j

N SU lnteger d ateC ount = [ d a t e L is t c o u n t] ;


f o r ( i n t i = 0 ; i < d a te C o u n tj i+ + ) {
NSDate *d = [ d a t e L is t o b je c t A t I n d e x : i] ;
NSLog(0"Here i s a d a te : %@", d ) ;

>
>

return

>

,^
fo r (
). :
#import <Foundation/Foundation.h>
int main(int argc, const char * arg v[])

0 autoreleasepool

/ / NSDate
NSDate *now = [NSDate date]j
NSDate *tomorrow =
[now dateByAddingTimeInterval:24.0 * 60.0 * 60.0];
NSDate *yesterday *
[now dateByAddingTimeInterval: -24.0 * 60.0 * 60.0]i
/ / *
/ / (n il - )
NSArray *dateList ,.
[NSArray arrayWithObjects:now, tomorrow, yesterday, ni Jj
for (NSDate *d in dateList) {
NSlog(0"Here is a date: %#", d);

>

>

return 0;

NSMutabteArrsy

109

?
6ops . :
.

NSMutableArray

NSArray .
u .
NSMutableArray NSArray,
. (NSMutableArray NSArray.
18.)
,
NSMutableArray:

NSMutableArray

#import <Foundation/Foundation. h>


int nain(int argCj const char * a rg v [])

autoreleasepool {
/ / NSDate
NSDate *now [NSDate d a te ];
NSDate *tomorrow *
[now dateByAddingTimeInterval; 240 * 60.0 * 6 0 .0 ];
NSDate *yesterday
[now dateByAddingTimeInterval:*24.0 * 60.0 * 60.0];

/ /
NSMutableArray * d a te tis t [NSMutableArray arra y ];

/ /
[d a te list addObject: now];
[dateLlst addObject:tomorrow];
/ / yesterday
(datelist insertQbject:yesterday atlndex:0]j

for (NSDate *d in d a te L is t) (
NSlog(f"Here is a date: %#", d);
&

110

15 NSArray

// yesterday
[d a te L lst rem oveO bjectA tIndex : 0] j
NSLog(@"Now the f i r s t date l s X", [d a te L ls t o b je c tA tir^ ,

>
re tu rn 0;
>

F o u n d a t i o n Grocerfe
NSMutableArray,
. ( .) , |
.
,
#im port < F o u n d atio n /F o u n d atio n . h>
i n t main ( i n t a rg c , c o n st c h a r * a r g v [ ] )
{

' ''']^

0 a u to re le a s e p o o l {

//
// ( )

N SString *nam eString


= [N S S tring stringW ithContentsO fFile:^"/usr/share/
d ic t/p ro p e rn a m e s "
e n c o d in g : NSUTF8StringEncoding
error:N U L L ];

//

NSArray *names = [n am eS trin g com ponentsSeparatedB yString:&

//
f o r (NSString *n in names) {

/ / - - ^.
NSRange r = [n r a n g e O fS t r ln g :fW options.N SCaseInsensiti*
Search];
// ?

111

i f ( r .l o c a t io n 1 NSNotFound) {
NSLog(@"X@", n ) ;

}
>

* return
}

0;

>
/usr/share/dict/propem am es
, /u sr/sh a re/d ict/w o rd s (
).
,
(Glen , glen ).
words .
,
.
c a s e In s e n s itiv e C o m p a re :
NSString * = @"";
NSString *b = @"";
i f ([a caseInsensitiveCompare:b] == NSOrderedSame) {
NSLog(@"a and b are equal");

>
i f ([a caseInsensitiveCompare:b] == NSOrderedAscending) {
NSLog(@"a comes before b");

}
i f ([a caseInsensitiveCompare:b] == NSOrderedDescending) {
NSLog(@"b comes before a");

NSArray
(
), .
Apple.
Xcode, Organizer
( X code)
Documentation.

. 16.1.

Apple :
I : Objective-C
.
:,
. ,

, Mac iOS
.
| : , ,
Apple . ,
WeatherMap ,
iOS.
eepcuu\ Mac OS
iOS ,
.
, , ,
:
.
, .
.


Organizer,
. NSArray;
. Reference NSArray,
NSArray.

. Apple
, .
.
,
, .
, , ( ,
, 17).
, .

Orfmlitr 1Do<umentetkm

& ^^
^ tywI
| *&
>***ffMV*'%CM
EjT
NSArray Class Reference
NSOW#tt
NSCodlng
NSCopyifig
NSMutabl*topy1np
NSfastfnumeutlon
NSObJatTfN50bjfttt)

NSArr#y

^^yCoM^fw

lyntmCuMn
m 1SMemKMrtn

- NSArray
, * NSArray
;^
O vtt FAQ
fA Memory Man*gemem Usmg Drtaj
_'_ fwchtnQ Min*fl*d Obj*cti
; : Table v>ew or out.. Co*urotof obJ*cr J
, - C o n tn d CO(o< KmtH^i
;,v '^ c o tttc H o n O p tm rto n
^ jC M b c M n O p f f tttf s
i^W SAfrayC**mHer
Toois C w H ti

Coco

Framework

ftysMm/Ubraty/Franwvorkt/Foundaiion.f'A<n***offc

AvaltabtIity

Av*itatMe in Mac 05Xvlo,o and later.

Declared ln

N5Arfty.h
NSKeyValueCodlng.h
NSKeyValueObservmg.n
NSPathUtUttiea.h
NSPredicaie.h
NSSorxOescriptor.h

Companion 9ukles

Co<kctions Programming topics


Key-Vatoe Coding Programming CuKfo
Property Ust Programming Guide
Pted*cate Programming Cuide

; s '', Sercng for an^ fr*w t w t o |


A S>w pte Code

Sfcaw4Me***jMuH*

| 7MMMyCMitfofltfi

$ tnMndvi

%| SowrceVMw
ft; EnhwrcA<K>*tMum
if QTKitMovtcShuffW

; ''

Rel*ied sample code CoreRedoes


FromAViewto AMovH>
Qti*ckLookSkch
5ketth+Accce4fbWty

Statth~U2

Bfl|ffre
. 16.2. NSArray

NSArray
. ,
N SO bject ( 18).
( 25).
Foundation Mac OS X
iOS.

NSArray , . Colkctions Programming Topics, .

( NSArray N SM utableArray).
, ,
.
,
NSArray.
NSArray?
, NSArray. , ,
? c o n t a in s O b je c t :
.

<ve*

16.3.

containsObject:
Retums a Boolean value that indicates whether a given object is present in the array.
-

( BOOL) c o n t a in s O b je c t s ( i d ) a n O b je c t

Parameters

anObject
An object.
Return Value
YES if anObject is present in the array, otherwise NO.
Discussion
This method determines whether anObject is present in the array by sending an
ieEquals message to each of the array's objects (and passing anObjecta% the parameter
to each isEqual s message).
Availability
Available in Mac OS X vl0.0 and later.
See Also

~ indexOfObject*
~ indexO fO bjeotIdenticalT oj
Related Sample Code

Sketch+AccessibHity
TimelineToTC
Declared In
N8A rra y.h

. 16.4. o containsObject:

11S

116

16


*i
.

, *
, .
Organizer D a te L is t. ^
[ d a t e L i s t a d d O b je c t:n o w ]. *
a d d O b je c t:.
.
@autoreleasepool {
// Create three NSDate objects
NSDate *now [NSDate d ate ];
NSDate *tomorrow = [now dateByAddingTimeInterval:2*
NSDate *yesterday = [now dateByAddingTimeInterval:// Create an array
NSMutableArray * d a teList = [NSMutableArray arrayI;
// Add the dates to the array
[dateList addObject:now];
[dateList ;add^ 'iect:tom orrow ];
O

addObject:

ffi

Name addObject:

Declaration:- fvoid)addOt>ject:(id)anObject
Avaitebility: Mac OS X(10.0 and later)
Abstract: fnserts a given obJta at the end of the array.
Parameters;
anObject: The object to add u> thc end ofthe array's content
Dedared im NSArray.h
Reference: NSMutableArray Class Reference
Related Documents: Collections Programming Topics, Key-Value
Coding Programming Guide

ig o f the
r atIndex:

. 16.5.

.
, O rg an ize r. ,
?
,
, Xcode. Xcodf
View,

117

gpgp^ggJi , Xcodc, /
/ <*
.
, ,
. , ,
.
( U t i l i t i e s ) . View,
Utilfties. ,
.
, .
: NSMutableArray:


Q OMUH ma*nm

|. (>j iiiB^ ffH


,M0 VN>

nWMn|OMW

.;

ftWMl

WM

/ / C reate th re e NSOat.e o b je c ts
NSJ>atc *oow * (NSOatc dateI;
HbUate *tonorrow (now d ate8yAcMlr*qTi^eIot
NSOni^ yesterday a [now rt<jtf*FyAddiogTtmr7n

*(|1<
A*Mrwa&#***M m

*^
nMMtfftt v*4*ftbt*ct* ?taM

?-
/ / re a te an array
NSHutabieArrey *d ateL ist

y *WrtHg *'aw Vh'W

O
nM
M
tftaM
Af^M
M*tMU *9 CtaM

toSMutai

/ / Add the dates t& the array


(dateList dddObjett:now]t
ldateList addOb}ect:tO0orrow);

Too*n. hv^M* <

(,

^
&mfaierip*inffb*th*, n ^ t-m,

/ / Put yesterday at tHe beginning of the Lil


(dateList insr* tO bjec r : yesterday at I nde**J]
for (NSDate *d in dateList) {
NSlog(&'Here is a date: *\ d);
I ;<S> St *

16.6.
,
, ,
.


Option,
Organizer .
,
Command, Xcode , -

118

16

. ( Command
. .

ableArray).

Run Stoo
Sriinmo ,.pipppi
IIe Ag*pTs: ^ Ti
/^^*^aMnMs***** Mutable
I V|SjQ*tcUu
i
1
| g in te rfa c e NSMutableArray : NSArray
; j omust.i
QSSupp0ftln9 Flttf

QgfrW9*rofki

i' ;.produCt*

| |~
I~

^gji&Ufe

' '>^nurfK*

p***************/

( v o id )a d d O b je c t:( id )a n O b je c t;
(v o id )in s e rtO b je c t:(id )a n O b je c t atIndex: (NSUInteger)index;
( v o id ) rem oveL astO bject;
( v o id ) removeObj e c tA tIn d e x : (NSUIntege r ) in d e x ;
(void)replaceO bjectA tIndex:(N 5U X nteger)index wlthObject:(id)anObjecf

Qend
in te rfa ce NSMutableArray (NSExtendedMutableArray)

. 16.7. NSMutableArray
,
Command . ,
Command addObject:.
Xcode ,
.
.
Xcode,
Apple http://
lists.apple.com/] .
,
. (
, , ,
,)
: stackoverflow.com.
, *
. ,
, , .

, Apple.
. ,
:
( ), ;
, .
Person, Person,
10. : Person.h Person.m.
Person.h, ,
. Person.m
. ,
.
: Foundation
BMITime.
, F ile New New File....
Mac OS X , Cocoa Objective-C
class. Person NSObject.
, , BMITime,
Save.
, Person.h
Person.m. Person.h,
:
#import <Foundation/Foundation.h>
/ / Person
/ / , NSObject
0interface Person : NSObject

&


120

17

'*

''"^ffiH i

//
flo a t heightlnMeters;
in t weightInKilos;

I
// ,
//
- (void)setH eightInM eters:(float)h;
- (void)setW eightInKilos: (int)w;
// ()
- (float)bodyMassIndex;

@end

: *
, .
:
P e rs o n ,
NSObject. :
f l o a t h e ig h tln M e te rs i n t weight*
In K ilo s . ,
Person.m.
s e tH e ig h tI n M e te r s : f l o a t
, s e tW e ig h tIn K ilo s : i n t
, bodyM assIndex
f l o a t .
P e r s o n . m.
, :
#import "Person.h"
^implementation Person
- (void)setHeightInM eters:(float)h

{
heightlnMeters = hj

>

- ( v o id )s e tW e ig h tI n K ilo s : ( in t) w

weightInKilos * w;

>

* (float)bodyM assIndex
{

return weightInKilos / (heightlnMeters h e i g h t ! n M e t e r s ) ; ^ ^ B

121

>
0end

, Xcode Person.h .
,
, . Xcode ;
, Xcode
.
, , Person.h, ; .
main.m, :
#import <Foundation/Foundation.h>
#import "Person.h"

in t m ain(int argc, const char * a r g v [])

@ autoreleasepool {
// Person
Person *person = [[Person allo c] in it ] ;
//
[person setWeightInKilos:96];
[person setHeightInMeters:1.8];
// bodyMassIndex
flo a t bmi = [person bodyMassIndex];
NSLog(0"person has a BMI o f %f", bmi);

>
return 0;

}
. Person.h ,
,

Bnain().

. 17.1.

122

17


, ^
m ain():
^

person.weightInKilos = 96;
person.heightInMeters = 1.8;

- ^
, ,
. Person ^
, s e tW e ig h tIn K ilo s : setHeig^,
InM eters:. s e t - ( )
Set- ^
Get- ( )
. S et- g e t- .
Person.h g e t-:
#import <Foundation/Foundation. h>
@ interface Person : NSObject

{
f l o a t heightInM eters;
i n t w eightInK ilos;

>
//
- (float)heightInMeters;

- ( v o id ) s e tH e ig h tI n M e te r s :( f lo a t) h ;
- (int)weightInKilos;

- (v o id )s e tW e ig h tIn K ilo s :(in t)w ;


- (float)bodyM assIndex;

0end
g e t- g e t
s e t -? Objective-C.

.
Person.m g e t -:
^implementation Person
- (float)heightInMeters

123

return h eightlnM eters;

|}

- ( v o id )s e tH e ig h tI n M e te r s :(f lo a t) h
{
heightlnMeters = h;
J}
- (int)w eightInKilos
{

return w eightInK ilos;

>
%- (void )setW eig h tIn K ilos:(in t)w

k|

w eightInKilos = w;

: >
- (float)bodyMassIndex

{
return w eightInK ilos / (h eig h tln M eters * heightlnM eters);

>
@end

main.m\
#import "Person.h"
int m ain(int arg c, const char * a rg v [])

{
@ autoreleasepool {
// Person
Person *person = [[Person a llo c ]

j>^'
in it ] ;

//
[person s e tW e ig h tIn K ilo s :9 6 ];
[person s e tH e ig h tIn M e te rs:1 .8 ];
// bodyMassIndex
f lo a t bmi = [person bodyMassIndex];

NSLog(0"person (%d, %f) has a BMI of %f",


[person w eightInK ilos], [person heightlnMeters], bmi)
}
return 0;

12 4

17

//

Objective-C . ~
1 ^ ,#
. **% I ,eJ u^
:
^ I ^ %
P = fx f i d o ] ;
p = x .f i d o ;

j / ^
I J jp j I

I J^ ^ i

[x s e tF id o :3 ] ;
x .f i d o = 3;

,
.
.
'
. I
,

| sdf

Person . Apple |
, , -
. set- g e t -
.

Person.h se t- g e t-
0property:
#import <Foundation/Foundation. h>
0interface Person : NSObject

{
flo a t heightlnMeters;
in t weightInKilos;

>
0property flo at heightlnMeters;
#property in t weightInKilos;
> (flo at)b o d yM assIn d ex;

0end

i
3fe
"*ig!

Ma AppJ,
;*

1X1

~
.
Person.m. , *


^ p r o p e r t y .
0 s y n th e s iz e :
#import "Person.h"
^implementation

Person

0synthesize heightInMeters, weightInKilos;

,
- (float)bodyMassIndex

return w eightInK ilos / (heightInM eters * heightInMeters);

>

: _,,: , :

,, ,;

@end
. , ,
.

self
i Apple

s e lf .
, . s e l f ,
. ,
Objective-C
;
, . bodyMassIndex,
:
- (float)bodyMassIndex
{
flo a t h = [ s e lf heightInMeters];
return [ s e lf weightInKilos] / (h * h);

}
P erso n , heightInM eters
w eightInK ilos, .
s e l f ,
. , Person
ad d Y o u rselfT o A rray : :

126

17

- (void)addYourselfToArray:(NSMutableArray *)theArray

{
>

[theArray addO bject:self];

s e lf ,
Person .

#$

: |
Person.m. ( Person.h , *|
.) j
, .
Objective-C.
. , ,
.
, .
Xcode ,
.

17.2. StockMolding

127

Foundation Stocks.
StockH olding .
^roT NSObject.
f lo a t purchaseSharePrice currentSharePrice
I n t numberOfShares.
.

^:
/ / purchaseSharePrice * numberOfShares
- (float)valueInDollars; / / currentSharePrlce * numberOfShares

- (flo a t)c o s tin D o lla rs ;

m aln() StockHolding.
.

Person NSObject.
Person
, NSObject, ,
Person. , Person NSObject. .
BMITime : Objective-C
Employee, N SO bject.
Employee P erson. , ?
(Employee) (P erso n ). .
.
,
, .
r
I
NSObject_______ |
}
i
I
I-- ____________________i
J (NSString *)description

**

*'

*
I
- ,*1
, int *
Jfloat heightInMeters
*.*(ftoet^xxiyMa&slndex j
i------------ 1..................

/
9

'^ w
-%
'
NSD ate............. " ~
NSStrtnfl----_"____
-1 -1
~~..~,*w . ,m
m~~mm mn<.1 i|
i i
".- -A^jy3BH
***#*+

4Hw*****M^*%fc**Mto^*MJb^'^*<*
&**^&*^*^**&^ ^0'^t^^w^ ^w
^**H
P**^-^*B
*l*,*,l***,l^4,l*l,^*,*^***^**^*^^*^**^^g^ek^^
- (ck>uble)timeintervalSince1970 - (NSUInteger)^vP;.---*

NSArray
- (NSUInteger)count;
..................................* ...................................

wherite from

tntmrtto trom
r

&mpk>ym9
*wrt #mpk>yMlD

. r

i
. . J . . . . v

. ,

NSMutabl*Array
4

%*+.*+~.*

(votd)addOb|ect:(k^)x;

i
i
i
t
i

18.1.

U9

Employee.h. Person.h,
person
:
#import "Person.h"
@interface Employee : Person

in t employeeID;

>

0property in t employeeID;
@end

Employeem :
#import "Employee.h"
^implementation Employee
^synthesize employeeID;
@end

Employee,
P e rso n employeeID.
Employee , Person.
, Em ployee setEmployeeID:
employeeID.
P erso n NSObject, Employee
NSObject. (
) N SO bject.
N SO bject ,
: i s a . i s a ,
.
, fid o .
, is a :
fid o ?
f id o , . ,
:
fido? f i d o
. fid o
. NSObject : , fido
>, -
Employee fid o .

130

18

............NSObject..........|
C lass isa
~^
- (NSString *Wescriptioiri

-----------------------------------

Person

fe*r**I *' " ?"*'*** ^^fc^.^

J int weightlnKilo
i float heightlnMeters
i - (float)bodyMasslndex
................... I .................

. 18.2.

main.m Persor
, :
in t m ain(int arg c, const char * a rg v [])
{

@ autoreleasepool {
/ / Person
id person = [[Person a llo c ] i n i t ] ;
/ /
[person setW eightInK ilos:96];
[person se tH e ig h tIn M e te rs:1 .8 ];
/ / bodyMassIndex
f l o a t bmi = [person bodyMassIndex];
NSLog(@"person (%d, %f) has a BMI o f %f",
[person w eig h tIn K ilo s], [person heightlnM eters], ^9 '*

[person count];
>

return 0;
}

U1

. (
, .
!)
:
*** Term inating app due t o uncaught excep tio n
'NSInvalidArgumentException*,
reason: -[P e rso n c o u n t]: unrecognized s e l e c t o r sen t to instance
0xl00108de0'

,
.
Employee, .
main.m, Employee:
#import <Foundation/Foundation.h>
#import "Employee.h"
int main(int argc, const char * argv[])

{
@autoreleasepool {
// Person
Person * person = [[Employee a llo c ] in it ] ;
//
[person setW eightInKilos:96];
[person setH eightInM eters:1.8];
// bodyMassIndex
flo a t bmi = [person bodyMassIndex];
NSLog(@"person (%d, %f) has a BMI o f %f",
[person w eig htInK ilos], [person heightlnMeters], bmi);

>

return 0;

: p e rso n -
Person. ?
, . ,
(Employee) (Person)
, . ,
Employee , Person.
, Employee,
- :

132

18

f ia p o rt

< F o u n d a tio n /F o u n d a tio n .h >

# i* p a rt

" E * p lo y e e .h -

in t m a i n ( i n t argc, const char * argv[])

0autoreleasepool {
// Person
Employee *person = [[Employee a llo c ] i n i t ] ;
//
[p e rs o n s e tW e ig h tIn K ilo s : 9 6 ];
[person setH eightInM eters:1.8];
[ p e r s o n s e tE m p lo y e e I D :1 5 ] ;

/ / b o d y M a ss In d e x
f lo a t bmi = [person bodyMassIndex];

>

N S L o g (0 "E m ployee Xd h a s a BMI o f % f" ,


[ p e r s o n e m p lo y e e I D ] , b m i ) ;

retu rn 0;


,
.
; ,
. , .
19.
bodyMassIndex Employee.
Employee.m :
# im p o r t "E m p lo y e e .h "
^ im p le m e n ta tio n Em ployee
^ s y n th e s iz e e m p lo y e e ID ;
-

( flo a t) b o d y M a s s In d e x

t
fend

re tu rn 19.0;
,

v - i^ ^ ^ ^ ^ ^ ^ ^ ^

133

,: . :
bodyMassIndex, Person.
1 bodyMassIndex Employee. m,
jEmployee.h.
, .
Employee Person, , Employee
$ bodyMassIndex. .

super
, ,
Person, 10%? ,
Employee,
bodyMassIndex Person 0,9,
. super.
Employee.m:
#import "Employee.h"
^implementation Employee
^synthesize employeeID;
I

- (flo a t)b o d y M a s s In d e x

I<
DBoa{

II

iM
tra

f l o a t normalBMI = [su p er bodyM assIndex];


return normalBMI * 0 .9 ;

@end

.
, super : ,
.

| .
| F o r e ig n S t o c k H o ld i n g , S to c k H o ld in g .
F o r e ig n S to c k H o ld in g
conversionRate, f l o a t . ( conver| *ionRate . ,

134

18

purchasePrice currentPrice .)
co stIn D o llars valueInD ollars. .
m a in ( )
ForeignStockHolding.

. 18.3. StockHolding ForeignStockHolding

,
, , in t flo a t.

.

. ,
:
: -
, N S S tring NSNumber. ,
Employee N SString.
Employee ,
N SString.
: .
, ; Employee
,
Person.

:
, NSMutableArray. (
21.) , ;
,
NSM utableArray
Person.
N S S trin g NSString.
, ,
.

13

19

. 19.1. Employee

, ( ). , Employee
: lastName, spouse children.
Employee :
0 in t e r fa c e Employee : Person

>

in t employeeID;
NSString *lastName;
Person *spouse;
NSMutableArray * ch ild ren ;

, employeeID, .
. *
spouse , &
spouse Employee, Person,
. . >*
( ),
, .
( )#11
:
. , *
, ^*
.

ARC

13 7

. 19.2.
.
,
(
).
,
. (, iPhone)
,
.

ARC

. , ,
, .
, ,
. , Person
: Employee Child.
, ,
, .
ARC (Auto
mated Reference Counting) - Objective-C .

138

19

Xcode 4.2
. ( 0
, 20. , *,
, , ARC.)
BMITime ,
. , ^
. J
Asset, Employee
, .

. 19.3.
/:
( Employee) (
NSMutableArray Asset).

Asset
NSObject. Asset. Asset.h, :
#import <Foundation/Foundation.h>
@in te rfa c e Asset : NSObject

{
>

NSString *label;
unsigned in t resaleValue;

0property (strong) NSString *label;


roperty unsigned in t resaleValue;

ARC

139

s t r o n g ( d p r o p e r t y
l a b e l . : ,
*. (
20.)
, , , .
d ealloc. (
dealloc NSObject.) dealloc
Asset.
, Asset , NSObject, d e s c r i p t i o n .
.
3K3eMmwpoBAsset eodescription ,
label resaleValue .
A sset.m .
, d e s c r ip tio n d e a llo c .
#import "A sse t.h "
^im plem entation A sset
^synthesize la b e l, re s a le V a lu e ;
- (NSString * ) d e s c rip tio n

return [NSString stringWithFormat:@"<%@: $%d >",


[ s e l f la b e l] , [ s e l f r e s a le V a lu e ] ] ;

, [ 6

>
- (v o id )d e a llo c

{
NSLog(Q"deallocating %@", s e l f ) ;

>
@end

%@
.
( ,
).
, ,
.
Command+B.
, ,
.

140

19

^
j ^
. , \ ^
.


Employee
Employee . ,
(, )
, .
,
:
,
.
,
.
Employee,
,
. .
Employee.h :
#import "Person.h"
0class Asset;

@interface Employee : Person

i n t employeeID;
NSMutableArray *assets;

>
@property i n t employeeID;
- (void)addAssetsObject:(Asset *)a;
- (unsigned int)valueOfAssets;

$end
@ class A s s e t;.
A sset. 111
, . @ class A s s e t ; *'

v
V*

flo 6 w u w w f * * Cmptoyti

141

t * . * HMCW*M A l l f t CyilU4*tHV<*T 1(* fw"tprtM fi * R *1

,
@class #import
uie , Mw
f c l i s s Hmpht/rr.h :* .
e 1111 i
.
kmployce.n\,
( ), | \r
- . ^
( Employee)
, .
#import "Employee.h"
#import "Asset.h"

^im plem entation Employee


^ s y n th e s iz e em ployeeID ;
- (void)addAssetsObject:(Asset * )a
{
/ / assets n il?
i f (!a s s e ts ) {

-;.
; - ?^&

/ /

assets = [[NSMutableArray a llo c ] i n i t ] ;

>

[assets addO bject:a];

>
- (unsigned in t)valu eO fA ssets
{
/ /

unsigned in t sum 0;
fo r (Asset *a in assets) {
sum += [a re sa leV alu e ];
>
retu rn sum;
>
- (flo a t)b o d y M a s s ln d e x

i
f l o a t normalBMI * [su p er bodyM assIndex];
r e tu rn normalBMI * 0 .9 ;

>

&

142

19

- (NSString * )d e sc rip tio n

{
retu rn [NSString stringWithFormat:0"<Employe* %d: $%d i n i l l f t
[ s e l f employeeID], [ s e l f v a lu e O fA s s e ts ]];

>

' ' '

' :' - :t

- (v o id )d e a llo c

j
N SLog(0"deallocating %@", s e l f ) ;

>

@end

E m ployee.m
A sset, Asset.h
@class.
d e s c r ip tio n dealloc
Employee.
, .
.
main.m:
# im p o rt < F o u n d a tio n /F o u n d a tio n .h >
# im p o rt "E m ployee.h"
#import " A s s e t.h "

K (|^ ^ ^ ^ ^ ^ ^ ^ H

i n t m a in ( in t a r g c , c o n s t c h a r * a r g v [ ] )

I
@ a u to re le a s e p o o l {
// Employee
NSMutableArray *employees = [[N SM utableArray a llo c ] in it];
f o r ( i n t i = 0; i < 10; i++) {

'^ K ': / )

// Employee
Employee *person = [[Employee a l l o c ] i n i t ] ;
//
[person s e tW e ig h tIn K ilo s:9 0 + i ] ;
[person se tH e ig h tIn M e te rs:1 .8 - i/ 1 0 .0 ] ;
[person setEm ployeeX D :i];
// employees
[employees ad d O b ject:p erso n ];

>

// 10 Asset
fo r ( in t i = 0; i < 10; i++) {
// Asset
Asset *asset = [[A sse t a llo c ]

in it ] ;

//
NSString * cu rre n tL a b e l =
[N SString strin g W ith Fo rm at:0"Laptop %d", i ] ;
[a sse t s e t L a b e l:c u r r e n t L a b e l] ;
[a sse t s e tR e s a le V a lu e :i * 17];
// 0 9
NSUInteger randomIndex = random() % [employees count];
//
Employee *randomEmployee =
[employees ob jectA tIn dex:random Index];
//
[ randomEmployee a d d A s s e ts O b je c t: a s s e t ] ;
}

/ ! ; ^ -

NSLog(0"Employees: %@", em ployees);


N SLog(0"Giving up ow nership o f one em ployee");
[employees rem oveO bjectA tIn dex:5 ];
NSLog(@G iv in g up ow nership o f a r r a y " ) ;
employees = n i l ;

>
re tu rn

0;

>

"

- " * * " 'W '

. :
Employees: (
"<Employee
"<Employee
"<Employee
"<Employee
"<Employee
"<Employee
"<Employee

0:
1:
2:
3:
4:
5:
6:

$0 in a sse ts> ",


$153 in a sse ts> ",
$119 in a sse ts> ",
$68 in a sse ts> ",
$0 in a sse ts> ",
$136 in a sse ts> ",
$119 in a sse ts> ",

&

144

19

"<Employee 7: $34 in assets>",


"<Employee 8: $0 in assets>",
"<Employee 9: $136 in assets>"

)
Giving up ownership of one employee
d ea lloca tin g <Employee 5: $136 in assets>
d ea lloca tin g <Laptop 3: $51 >
d e a llo ca tin g <Laptop 5: $85 >
G iving up ownership o f array
d e a llo ca tin g <Employee 0: $0 in assets>
d e a llo ca tin g <Employee 1: $153 in assets>
d e a llo ca tin g <Laptop 9: $153 >
d e a llo ca tin g <Employee 9: $136 in assets>
d e a llo cin g <Laptop 8: $136 >

Employee 5
, . , . (
: , N SString,
, .)
employees n i l, ., ,
, Employee
.
, ? , .
- , , .
,
. iOS
. Mac OS X
,
.

S tockH olding , g ?
, P o r t f o l i o ( )^
StockHolding .
P o r t f o l i o .

I . ,
,
. .
. 20.1.
holder
_______ Asset_______ tabel &

_.
Employee

employees

heightlnMeters = 1.8
weightInKilos = 96
employeeID = 0

Asset

~~*
assets

(void)addAssetsObject:(Asset *)a;
- (unsigned int)valueOfAssets;

P*

resateValue = 51_______
label

NSString
@Taptop T

resaleValue = 119

holder

Employee
heightlnMeters = 1.7
weightInKilos = 98
employeeID = 1

NSString
"Laptop3*

Asset

assets

resateValue = 34

tebet r

NSString
"Laptop 2"

- (void)addAssetsObject:(Asset *)a;
- (unsigned int)valueOfAssets;

holder

. 20.1.


( A s s e t) ( Employee).
Asset.h
:

146

20

#import <Foundation/Foundation.h>
#class Employee;

' "^ ^ 'r


| *j

@interface Asset : NSObject


{
NSString *la b e l;
Employee *holder;
unsigned in t resaleValue;
>

@property (strong) NSString *la b e l;


#property (strong) Employee *holder;
@property unsigned in t resaleValue;
@end

Asset.m descriptio n , :
#import "Asset.h"
#import "Employee.h"

_,

h-&&k

@implementation Asset
@synthesize la b e l, resaleValue, holder;
- (NSString *)description
{
/ / n il?
i f ( [ s e lf holder]) {
return [NSString stringWithFormat:#"<%0: $%d, assignedtoX0>
[s e lf la b e l], [s e lf resaleValue], [s e lf holder]];
> else {
I \ . * M i , L . [
return [NSString stringWithFormat:$"<%$:$%d unassigned>"
[s e lf la b e l], [s e lf resaleValue]];
>

u ^
i I
. . . ___ _________________ ta

(v o id )d e a llo c

_______ _ 9_.N
% ,'
C

{
N S L o g (@ "d eallo cin g %@", s e l f ) ;

>

>

@end

'4
^
: Asse* ^
Em ployee ? , 1 ^
. &
, . |
^

147

:
[vicePresident addAssetsObject:townCar];

[townCar setH older:viceP resident];

, ,
:
- (void)setHolder:(Employee *)e

holder = e;
[e addAssetsObject:self];

}
.

, ,
.
.
Employee.m a d d A s s e ts O b je c t:,
h o ld er:
- (void)addAssetsObject:(Asset *)a

// n il?
i f (!assets) {
//
assets = [[NSMutableArray a llo c ] i n i t ] j

'''* * &

}
[assets addObject:a];
[a se tH o ld e r:se lf];

( : . : addAssetsObject:
setH older: , addA ssetsO bject: ,
setHolder:, ...)
. *
Employees: (
"<Employee
"<Employee
"<Employee
"<Employee
"<Employee
"<Employee

0:
1:
2:
3:
4:
5:

$0 in assets>",
$153 in assets>",
$119 in assets>",
$68 in assets>",
$0 in assets>",
$136 in assets>",

"<Employee 6: $119 in a s s e ts > " ,


"<Employee 7: $34 in assets>",

148

20
"<Employee 8: $0 ln assets>",
"<Employee 9: $136 in assets>"

G iv in g up ownership o f one employee

Giving up ownership o f
deallocating <Employee
deallocating <Employee
deallocating <Employee

array
0: $0 in assets>
4: $0 in assets>
8: $0 in assets>

: , i
, . . ?


,
,
.
, . .

- Apple, Instruments.
,
.
, .
, main() sleep()
:

.}
}

sleep (100 );
return 0;

Xcode Product Profile;


Instruments. Leaks ^1
(. 20.3).
Allocations , .
, , 10 Aset'
, .
Leaks Cycles - ^P*1
(. 20.

^
Choon T W i TtmpiiH or f*f*tinq

Mftt 01X

M
*mc*Y

1|Syttcm
Pfhj\rlOf

fltanfc

X Uw

i
Ope**
Rtc*nt

ActivHy

Momtof

Tlm* N M v

Mvtaco*t

Leaks

MfMur*t flerwwl mrmorv uwg#. ctocks for <eaked mtnwy. and provMti iw<iBo oft
obJffct attocarion* by class w*ll u meroory n M w i hluorle* for *t' rwe ettaeMfo*it and
<eaked Mock*.

. 20.2.

Instruments

tnstrument Deiail

fW^^^^^^^^^

Attocaik>ns

v Hwp*boji*>^>ri

**
:1VOfc*mO*Mrf
*CfMKdftSB0ijRM9
*i D>sirwt*
? <
5**
'fepmNt*vtwt*d

&JMR4HflW
HUt MtaM^ Sy*flbcH

HMtiy4w>Uterirt
ftw0^-Orty
HOW
ftKU>W
Oft
i *
*

QP

00^^^^^^^

'

83 StaiisOcs > / Object Summary


rf^Jh iCttafOfy
-3fcv Liv*MM
AiI Aiiocaoons
124.?2
336Bytes
Q Asset
CFBaskHft5h
656BytM
CFBaswBash 0tcy-store)
224 Bytes
CF6aaicHash (vaiue~st.
288 8ytes
j CFBundk
144 8ytes
CFlocai*
84
OFNottftcat*onC*mer
160Bytes
.1 CfSwnj
1.06
CFScrtng (store>
560
64
CfURL
Employee
272
Maltoc 16 Bytes
1.77
MaAoc 32 ^M t
LS6K8
Mafioc 48 Bytcs
1.83KB
64
6.06
80 8yus
2.11 K8
.' Mafioc 112 ftytes
1.42 KB
Mattoc 128
4,50KB
720
MaHoc 144
Mattoc 180 Bytes
1.56KB
Mattoc 178 *
880
M*Hoc 208
416

9&&&&1&^^CPftftW
WjfiffiflKjifrft6jy1

#Uving * Transftory
524
10
11

7
8
I
I
2
21
6
1
8
113
50
39
97
27
13
36

s
10
s
2

0
0

0
0
0
0
0
0

0
0
0
0
0
0

0
0
0
0
0

Overaii Bytes
114.72K8
336
656
224
288
144
64
360
1.06K8
560
64
272
1.77
l-56KB
1.83K8
6.06
2 11
1.42
4-S0
720
l.S6
880
416

20.3. Allocations

OveraH 9 AHocation* flS>i


S24^
10
M

7
*m
1
&t
Z|

21
l i

8
113
S0
39

__________

97

27
13
36
59

10
sa
21

149

150

20

Instrum ents

& )

ao oo 3BQ I Sa'U^-'
8I I . ' .. I Ittomt
jI
pfvf I

/
W

* -

iMfcs

[
MiMfei

[tfA*aw<US4f
hapMMMiM MJ
tan Ml

le0*to#**y

r>

ffi
t S Cydes $ LeokCydes
it! # Cyc*t _
'^
0 *tPptow - 5 nodes
1 fa ploH - 4 nodes
2 EmtHoyre - S nodes
3 twplw i - S nodes
4 *fm p to yM - 4 nodes
5 fmptoyw - 4 nodes

OeSaSls

Cyck Graph

Compfcx Cydi
SimpieCydc
Compf#x Cycle

CompfexCyde
5*mp(e Cycle
SimpteCyde

p i ^
& 1
M TfiXi

. 20.4. Leaks

tim
port
fim
por1
ftim
porl
int :


?
. ,
.
. Asset.h,
:
#import <Foundation/Foundation.h>
#class Employee;
#interface Asset : NSObject

>

NSString *label;
_weak E&ployee *holder;
unsigned in t resaleValue;

iai

151

0property (s tro n g ) NSString * l a b e l ;


0property (weak) Employee * h o ld er;
0property unsigned i n t re s a le V a lu e ;

end
. ,
.
/^
: ,
.


,
. ,
, .
.
main.m:
#import <Foundation/Foundation.h>
#import "Employee.h"
#import "Asset.h"
int main(int argc, const char * a r g v [ ] )
{
@ autoreleasepool {

''

// Employee

NSMutableArray *employees = [[NSMutableArray a l l o c ] i n l t ] ;


f o r ( i n t i = 0; i < 10; i++) {
/ / Employee
Employee *person = [[Employee a l l o c ] i n i t ] ;
//

[person setW eightInK ilos:90 + i ] j


[person setH eig h tIn M e ters:1 .8 - i / 1 0 . 0 ] ;
[person setEmployeeID:i];
// employees

[employees ad d O b ject:p erso n ];


^

&

152

20

NSMutableArray *allAssets * [[NSM utableArray a llo c ] l n i t j .

/ / 10 A sset
f o r ( i n t i = 0; i < 10; i++) {
/ / A sset
A sset * a s s e t = [[A s s e t a l l o c ] i n i t ] ;
/ /
N SString * c u rre n tL a b e l = [N S S tring
strin g W ith F o rra a t: @"Laptop % d " , i ] ;
[ a s s e t s e tL a b e l: c u r r e n tL a b e l] ;
f a s s e t s e tR e s a le V a lu e :i * 17];
/ / 0 9
NSUInteger randomIndex = random () % [em ployees count];
/ /
Employee *randomEmployee = [em ployees
o b je c tA tI n d e x : random Index];
/ /
[ randomEmployee a d d A s s e ts O b je c t: a s s e t ] ;

[ a l l A s s e t s a d d O b je c t: a s s e t ] ;

N SLog(#''Em ployees: %@, e m p lo y ees);


NSLog(# "G iv in g up o w n ersh ip o f one em ployee) ;
[em p loyees rem o v e O b je c tA tIn d e x :5 ];
N S L o g (# " a llA s s e ts : %gm, a l l A s s e t s ) ;
N S L og(#"6iving up o w n ersh ip o f a r r a y s " ) ;

>

a l l A s s e t s * n il;
e ^ ) lo y e e s n i l ;

s le e p (1 0 0 );

>

return 0;

'f^fc*^3^

, ^
. allAssets ~* _^
E m p lo y ee 5. *

: ARC

153

0 ? ( E m ployee
5 ), - a l l A s s e t s ,
^ .
h o l d e r ,
Employee 5 ? ,
, , n i 1.
E m p lo y ee 5 ,
h o l d e r .
:

Employees: (
"<Employee 0 : $0 i n a s s e t s > " ,
"<Employee 9: $136 i n a s s e t s > " <ri

)
Giving up o w n ersh ip
d e a llo c a tin g
a llA s s e ts : (
"<Laptop
"<Laptop
"<Laptop
"<Laptop
"<Laptop
"<Laptop
"<Laptop
"<Laptop
"<Laptop
"<Laptop

o f one em ployee
<Employee 5: $136 i n a s s e t s >

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

$ 0 , a s s ig n e d t o <Employee 3 : $68 i n a s s e t s > > " ,


$ 1 7 , a s s ig n e d t o <Em ployee 6 : $119 i n a s s e t s ft,
$ 3 4 , a s s ig n e d t o <Em ployee 7 : $34 i n a s s e t s " ,
$51 u n a s s i g n e d > ' \
$ 6 8 , a s s ig n e d t o <Em ployee 3 : $68 i n a s s e t s > > " ,
$85 u n a s s i g n e d >" ,
$102, a s s ig n e d t o <Em ployee 6 : $119 i n a s s e t s " ,
$119, a s s ig n e d t o <Em ployee 2 : $119 i n a s s e t s " ,
$136, a s s ig n e d t o <Em ployee 9 : $136 i n a s s e t s > > " ,
$ 153, a s s ig n e d t o <Em ployee 1 : $153 i n a s s e t s "

G iving up o w n ersh ip o f a r r a y s
d e a llo c in g <Laptop 3: $51 u n a s s ig n e d >
d e a llo c in g <Laptop 8 : $136 u n a s s ig n e d >

:
ARC
19, Objective-C
ARC (Automatic Reference Counting)
,
,
.

154

20

[anObject re le a se ]; / / anObject
[anObject re ta in ]; / / anObject

(retaih
, release ' ^
dealloc ( ) f
setHolder: ^accaAsset :
- (void)setHolder:(Employee *)newEmp
{
[newEmp re ta in ]j
[holder re le a s e ];
holder = newEmp;

'

- -* * * *

dealloc:
- (v oid)dealloc
{

' - ;

[la b e l re le a s e ];
[holder re le a s e ];
[super d e a llo c ];

'. '^ j > ^ ^ 1

description? .
Asset ? , -
. autorelease, release . ARC
description Asset :
- (NSString * )d escrip tio n
{

NSString * re s u lt = [[NSString a llo c l initWithFormat:@"<%@: $%d >",


[ s e lf la b e l] , [s e lf
resaleV alu e]];
[ r e s u lt a u to re le a se ];
retu rn r e s u lt;
>

release? autorelease:
/ / autorelease
NSAUtoreleasePool *arp = [[NSAutoreleasePool a llo c ] i n i t ] ;
Asset *asset = [[Asset allo c] i n i t ] ;
v

NSString *d = [a sse t d e sc rip tio n ];


/ / , d ,
[a rp d r a in ];

/ /

a u to re le a s e

r e le a s e

155

ARC a u to r e le a s e ,
. ARC
autorelease.
:
/ / autorelease
^autoreleasepool {
Asset *asset = [[Asset a llo c ] i n i t ] ;
NSString *d = [asset description];
/ / , d, autorelease
} / /


,
Objective-C. ARC,
.
,
. :
, ,
. , ,

, , ,
.
, ( ).
, a llo c
new , . (
, 1
autorelease.) ,
. ,
: a llo c (
in it) , mutableCopy.
,
. ( , 1
a u to re le a s e ,
,
autorelease.)

156

20

, , /,
, , retairu,4
).
I ,
release autorelease. ( release *
, autorelease coo6n^
release .)
I ,
( , .
dealloc.)
,
. A sset
, .
, Asset ,
, .
, | :
. .

, ,
.
,
autorelease description :
, .


: NSArray NS
MutableArray. ,
. ,
( ).
,
: NSSet/NSMutableSet N SD ictionary/N SM utableD ictionary.

NSArray/NSMutableArray

'--,^^

.
, .
BMITime ,
employees. ,
:
// Employee
NSMutableArray *employees = [[NSMutableArray alloc] in it ] ;
for (int i * 0; i < 10; i++) {
//
Employee *person = [[Employee alloc] in it ] ;
// employees
[employees addObject:person];

>
[employees removeObjectAtIndex:5];
employees = n il;

158

21

, (mutable)
l o c / i n it . , $
:
''^
NSMutableArray *employees = [NSMutableArray a r r a y ] ;

addO bject : .
, ^ ^ ^
.

NSArray ,
. :
NSArray *colors = [NSArray arrayWithObjects:@"Orange", @"Yellow",
@Green", n il] ;

n il , . colors
. ( nil, , }'
.)

NSArray. , ?
:
, . ,
, . ,
NSMutableArray,
NSArray. , :
/ / 30
- (NSArray *)odds

>

return odds;
}

s ta tic NSMutableArray *odds = [[NSMutableArray alloc] i n i t ] ;


in t i = 1;
while ([odds count] < 30) {
[odds addObject:[NSNumber numberWithInt:i];
i += 2;

, , ,
NSArray.
,
NSMutableArray.

; .
,
,
. .
, N SM utableA rray
, NSArray
.

Objective-C. Foundation
: NSA rray, N S S trin g , N S A ttrib u te d S trin g , NS
Data, N S C haracterS et, N S D ic tio n a ry , NSSet, N SIndexSet NSURLRequest.
: NSM utableArray, NSM utableString,
N S M u tab leA ttrib u ted S trin g . . NSDate NSNumber
, .

,
.
NSMutableArray :
- (void)sortUsingOescriptors:(NSArray *)sortDescriptors;

N S S ortD escriptor.
, ,
( ).
? , I .
I ? I , :
I ;
I , , I & .

160

21

NSSortf>Mcrfptor
key * ^HastName*
ascending * YES

S'

Iz

NSSor1De*crlptor
key as @^rstName'
ascending = YES

NSSortDMCriptor
key = @HzipCode*
ascending = YES

21.1. lastName,
firstName zipCode

, ,
.
BMITime ,
. m ain(), employees
valueO fA ssets. ,
em p lo yeeID . main.m\
}

'V * 7 # ^ H H
%

NSSortDescriptor *voa =
[N S S o rtD escrip to r sortDescriptorWithKey:0"valueOfAssets"
ascending:YES];
N S S o rtD escrip to r * e i =
[NSSortDescriptor sortDescriptorWithKey:0"employeeID"
ascending:YES];
[employees sortUsingDescriptors:[NSArray arrayWithObjects:voa,
e ij n i l ] ] ;
^ ? |^ ^ ^ ^
NSLog(0"Employees: %@", employees);

. ,
:
E m ployees: (

"<Employee 0: $0 in assets> ",


"<Employee 4: $0 in assets>",
"<Employee 8: $0 in assets>",
"<Employee 7: $34 in assets>",
"<Employee 3: $68 in assets>",
"<Employee 2: $119 in assets>",
"<Employee 6: $119 in assets>",
"<Employee 5: $136 in assets>",
"<Employee 9: $136 in assets>",
"<Employee 1: $153 in assets>"

161

N SPredicate ,
, : employeeID 75.
NSMutableArray ,
:
- (void)filterU singP redicate:(N SP redicate *)predicate;

NSArray , ,
:
- (NSArray * )filtered A rrayU sin gP red icate:(N S P red icate *)predicate;

, , ,
$70.
main.m :
[employees removeObjectAtIndex:5];
NSLog(@"allAssets: %@", a llA s s e t s ) ;
NSPredicate *predicate = [NSPredicate predicateMithFormat:
@ "holder.valueO fAssets > 70"];
NSArray *toBeReclaimed =
[ a llA s s e ts filte re d A rra y U s in g
P re d ic a te :p re d ic a te ];
NSLog(0"toBeReclaimed: %@", toBeReclaimed);
toBeReclaimed = n i l ;
NSLog(@"Giving up ownership o f a rra y s " );
a llA sse ts = n i l ;
employees = n i l ;

>

>

*p*

return 0;

- i ||

.
:
toBeReclaimed: (
"<Laptop 1: $17, assigned to <Employee 6: $119 in assets>>",
"<Laptop 3: $51, assigned to <Employee 5: $136 in assets>>",
"<Laptop 5: $85, assigned to <Employee 5: $136 in assets>>",
"<Laptop 6: $102, assigned to <Employee 6: $119 in assets>>",
"<Laptop 8: $136, assigned to <Employee 9: $136 in assets>>",
"<Laptop 9: $153, assigned to <Employee 1: $153 in assets>>

21

162


,|
Predicate Programming Guide* ^

NSSet/NSMutableSet

" I

,
.
.
, , : ? ,
URL-, .
- , ,
URL- .
.

.
, NSMutableArray
NSMutableSet.
holder

__________ Employee
heightInMeters = 1.8
welghtlnKllos = 96
emptoyeelD 0

assets

- (Void)addAss0 tsObject:(Asset *)a;


(unsigned tnl)valueOfAasets;
effiptoyees

I ' holder

Employee
heightInMeters 1 .7
weightInKilos = 98
emptoyeelD = 1
(vold)addAsaetsObject:(As3et *)a;
- (unsigned lnt>valuaOIABsats;

resaleValue = 34

N89trtQ8

Laptop ?

holder

. 21.2. NSMutableSet

Employee.h :
#import "Person.h"
@ class A sset;

NSSet/NSMutableSet

153

^ in te r f a c e Employee : Person

i n t employeeID;
NSMutableSet * a s s e t s ;

>

0property I n t employeeID;
- (v o id )a d d A s s e ts O b je c t:(A s s e t * )a ;
- (unsigned i n t ) v a lu e O f A s s e ts ;

0end
Employee.m :
- (v o id )a d d A s s e ts O b je c t:(A s s e t *)a

{
i f (!a sse ts) {
a s s e t s = [[NSMutableSet a l l o c ] i n i t ] ;

}
[ a s s e t s a d d O b je c t:a ] ;
[a s e t H o l d e r : s e l f ] ;

>

. ., S J ,m '

. ,
.
,
. :
? NSSet :
- (B O O L )containsO bject:(id)x;


, x. ,
YES; N0.
:
? NSObject is E q u a l:,
:
i f ([myDoctor is E q u a l:y o u rT e n n is P a rtn e r]) {
NSLog(@"my d o cto r i s eq u al to your te n n is p a r tn e r " ) ;
}

.''^^^f^*

NSObject is E q u a l:. :
- (B O O L )isE qual:(id)other
{
re tu rn ( s e l f == o th e r ) ;
>


'| | g |

, isE q u a l:
:

164

21

i f (myDoctor * yourTennisPartner) {
NSLog(@my doctor is equal to your tennis p artn er");

>

'

isEqual:. , N S S t r i n g
isEqual: . *
. , 8
:
NSString *x = . . .
NSString *y = . . .

x , .
x , , ,
, .
, ,
.
? , . , NSM utableArray
:
- (NSUInteger)indexOfObject:(id)anObject;
- (NSUInteger)indexOfObjectIdenticalTo:(id)anObjectj

,
isEqual: anObject.
== anObject.

NSDictionary/NSMutableDictionary
,
; :
10. ( ) ;
:
fa v o rite C o lo r> . ,
/. ,
. / -
.
.
Employee.
@"" ( ), 0'*CTO
( ). main.m\
N SM utableD ictionary, <*4

NSDictlonary/NSMutableDlctionary

165

. , n i l , ,
.
// Employee
NSMutableArray *employees = [[NSMutableArray a llo c ] i n i t ] ;
// executives
NSMutableDictionary *executives =
[[NSMutableDictionary a llo c ] i n i t ] ;
for (in t i = 0; i < 10; i++) {
// Employee
Employee *person = [[Employee a llo c ] i n i t ] ;
//
[person setW eightInK ilos:90 + i ] ;
[person setH eightInM eters:1.8 - i/ 1 0 .0 ] ;
[person setEm ployeeID :i];
// Employee employees
[employees addO bject:person];
// ?
i f ( i == 0) {
[executives s e tO b je ct:p e rso n fo rK ey:0 "C E O "];

>
// ?
i f ( i 1) {
[executives se tO b je c t:p e rso n fo rK e y :g "C T O "]j

>
}

NSLog(@"allAssets: %@", a llA s s e t s ) ;


NSLog(@"executives: %@", e x e c u tiv e s );
executives = n i l ;
NSPredicate * predicate , [N SPredicate predicateW ithForm at:
@ "h o ld e r.v a lu e O fA sse ts > 70"];
NSArray *toBeReclaimed = [ a llA s s e t s filt e r e d A r r a y U s in g
P r e d ic a t e : p r e d ic a t e ] ;
NSLog(@"toBeReclaimed: %@", toBeR eclaim ed);
toBeReclaimed n i l ;*

166

21

NSLog(@"Giving up ownership o f a r r a y s " ) ;


a llA s s e ts
employees

n il;
n il;

}
re tu r n 0;
>

. :
e x e c u tiv e s = {
CEO = "<Employee 0: $0 in a s s e ts > " ;
CTO = "<Employee 1: $153 in a s s e ts > " ;
>
holder

_______ Asset
lebel
resaleValue = 51______

executives

Employee
heightInMeters = 1 8
weightfnKik>s = 96
empioyee!D = 0
(void)addAssetsObject:(Asset ')a;
- (unsigned int)vatueOfAssets;

assets

NSString
0"Laptop3"

aHAssfls

Asset
fabei ^ NSString
resaleValue = 119_____
HLaptop7*

Employee
heightInMeters = 1.7
weighilnKik>s = 98
empioyeetD = 1
- (void)addAssetsObjecL(Asset *)a;
(unsigned irrt)valueOfAssets;____

holder

. 21.3. Employee NSMutableDictionary

.
/.
/ /
N SM utableD ictionary * frie n d s = [N SM utableD ictionary d ic tio n a r y ] ;
/ / "b e stF rie n d "
[ f r ie n d s s e tO b je c t:b e tty forK ey:@ "bestF riend"];
/ /
[ f r ie n d s s e tO b je c t:ja n e forK ey:@ "bestF riend"];
|
/ / frie n d s "/" (b estF rien d => j ane'


, ,
f l o a t , in t

167

.
, . NSNumber
, a NSValue .
, 4 5,6
NSNumber:
NSMutableArray *numList = [ [NSMutableArray a llo c ] i n i t ] ;
[numList addObject:[NSNumber numberWithInt:4]];
[numList addObject:[NSNumber num berW ithFloat:5.6]];

nil
, , n i l.
, ?
NSNull.
, . :
NSMutableArray *hotel = [[NSM utableArray a llo c ]

in it ] ;

//
[hotel addO bject:lobby];
// ,
[hotel ad d O b ject:p o ol];
//
[hotel addO bject:[N SN ull n u l l ] ] ;
//
[hotel addObject:bedroom s];

NSArray, NSMutableArray, NSDictionary NSMutableDictionary.


.

, ,
, .
, (,
, n). .
Objective-C :
# d e fin e .
Xcode Foundation
C onstants.

#define.
math.h. , M_PI.
main.m\
#import <Foundation/Foundation.h>
i n t main ( i n t argc, const char * a rg v [])

{
@autoreleasepool {

/ / NSString
// \u
NSLog(0"\u03c0 is %f", M_PI);

>

retu rn 0;

>

* t^

^H
-/m ^ ^ M

. :

i.tMi|Hvuui<'iint< KoiH iHii i t.i M f*1, pgJfb


. ............. Commancl, l!l,<vi-i()K
( i|H*Kv ii

niath,h:

#de1 in* M...Pl

\ . 1 4 aS 9 2 6 R3 5 fl0 7 9 3 2 3 8 4 6 a 6 4 ia B 3a 7 9 S0 2 gB

, ( ' + * <)|>jeelive ( '


. , 1 ' i n n J>eay i\tnw\
IH*p<Via<*K H . ^ (
ft', 0@@
t lude, Wtmport
#define

#include and #import

,,i

#include #import :

(<
,);
.
#intludi WimportV #import tapaniitpyet,
pa i, ttlnc iudfi noinoanti
I! #include,
anpofpaMMH< iM ()bjg( tive ( ' Blmport
01 6f?I1
(:tu/)KH , 1
cKia !, i
, np<4ipoijeec<>py. (, - n m i h h Kai / e / / )^v0lopeT/Sl)Ks/MtU ().SX 10 7s<lh/usi/tii(lit<lr t mt i hh)
| | Wlmport
/ / Hvn*rninnt- @@@8/ H**t f t0 P g

#iwpert "P#fcitere#ft"
/ / b ttw s* v\ @ 0 OpfefiM>AH

#i*p0f4 <l4ap,H>

Kin/m td iipo#KT e np<a


'\mwA * ,tto 1
^ Hpoi pafioram, g nixi

170

22

, Xeod#
, ^ ^
. Constants &^
'oTisf(ints-f*rr/i\\j)ch.

, mnth.h
main.m? 1laiu . moin.m :

#import <Foundation/Foundation.h>

Foundation.h :
# in clu d e <CoreFoundation/CoreFoundation. h>

CoirFoundation.h :
#include <math.h>

#define
#define : , * X, V , .
math.h:
# d efin e M_PI

3.14159265358979323846264338327950288

#define ( )
.
, #define
. main.m :
#im port <Foundation/Foundation.h>
i n t main ( i n t arg c, co n st char * argv[])

{
0 a u to re le a se p o o l {

'; i | ^ ^ K U

NSLog(0"\u03c0 i s %f", M_PI);


NSLog(0"%d is l a r g e r " , MAX(10, 1 2 ));

.:v4^---j

re tu rn 0;
>

, a # d efin e. 1 |
# d efin e MAX(A,B)

((A) > () ? () : (B))

^^

, ,
:

/vf oH*
,

i7 i

NSLog(0"%d is l a r g e r " , ( ( 1 0 ) > ( 1 2 ) ? ( 1 0 ) : ( 1 2 ) ) ) ;

# d e fin e (
), , .

#define Objective-C
.
. NSLocale , ,
. ,
,
. , ,
, :
#import < F oun dation/F oundation. h>
in t main ( i n t a r g c , c o n s t c h a r * a r g v [ ] )

{
@ autoreleasepool {
NSLog(@"\u03c0 is %f", M_PI);
NSLog(@"%d is la rg e r", MAX(10, 12));
NSLocale *here = [NSLocale currentLocale];
NSString *currency = [here objectForKey:0"currency"];
NSLog(@"Money is %@", currency);

>

re tu rn 0;

>

,' V * * -

. , ,
:
Money is USD

(, @"Kuruncy"),
.
Foundation NSLocaleCurrencyCode. ,
, . ,

172

22

Xcode ,
@ "". , * ^^
#im port < F oundation/F oundation.h>
i n t main ( i n t a rg c , c o n st ch ar * argv[])

@ autoreleasepool {
NSLog(@"\u03c0 i s %f", M_PI)j
NSLog(@"%d i s l a r g e r " , MAX(10, 1 2 ) ) ;

. *
;- ^
- , . !?;^ | ^ |

NSLocale *here = [NSLocale c u r r e n tL o c a le ] ;


N SString *currency = [h e re objectForKey:NSLocaleCurrencyCodelNSLog(@"Money i s %@", c u rre n c y );

>

re tu rn 0;

-^ > ^ ^ ^ B H

'-'^ :

NSLocale
. NSLocale.h :
e x te rn N SString co n st *NSLocaleCurrencyCode;

const ,
. extern
: , , .
, NSLocale.m :
NSString co n st *NSLocaleCurrencyCode = @ "currency";

enum

v.'*

. ,
. Blender
setSpeed: . , , *
.
, '.
enum BlenderSpeed {
B lenderS peedS tir = 1,
BlenderSpeedChop = 2,

B lenderSpeedLiquify = 5,

enum

173

B len d erS p ee d P u lse * 9 ,

BlenderSpeedIceCrush = 15
};

0interface Blender : NSObject


{
//

enum BlenderSpeed speed;


>

/ / setSpeed:
- (void)setSpeed:(enum BlenderSpeed)x;
0end

enum B l e n d
e rS p e e d .
ty p e d e f:
typedef enu*

BlenderSpeedStir = 1,
BlenderSpeedChop = 2,
BlenderSpeedtiquify = 5,
BlenderSpeedPulse = 9,
BlenderSpeedIceCrush = 15
} BlenderSpeed;
gL nterface B lender : NSObject
{

, /
BlenderSpeed sp eed ;

*-*
.,y ^ m m

>

// setSpeed: *
I (voi6)setSpeed:(B IenderSpeed)x;

gend
,

6 .
*** ,
**:
typedef {
81ef>derSpeedStir,
BUoderSpeedChop,

51enderSpeedLdLquify,
- lenderSpee<JPu l s e ,
SlenoerSpeedIceC rush
) ile n d e rS p e e d ;

174

22

#define
#define,
( enum), Objective-C ?
. ,
== isE q u a l: (
). ,
.
enum, #define.



NSString NSData

Foundation
. .

NSString
NSString.
,
. ASCII 'A'
01000001, UTF-16 'A '
0000000001000001.
Foundation 20 .
UTF
. : UTF-16
, UTF-8 128 ASCII
, .
UTF-8 .
: Foundation
Stringz. m ain() N S S trin g
:
#import <Foundation/Foundation.h>
int main (in t argc, const char * arg v [])

xP^

176

23 NSString NSData

0autoreleasepool {
NSMutableString * s t r * [[NSMutableString a llo c] in it ] ;
fo r ( in t i * 0; i < 10; i++) {
[s tr appendString:Aaron is c o o l!\n ''];

>

[ st r w rite T o F ile : $"/tm p/cool. txt'*


atomically:YES
encoding:NSUTF8StringEncoding
error:NULL];
NSLog(0"done w ritin g /tm p /c o o l.tx t" );

>

re tu rn 0;

>
,
. /tm p /c o o l.tx t .

;
/ , ,
.
/ . Objective-C
,
. ( /tmp Finder,
Go Go to Folder.)

NSError
.
, ,
. .
. , *
, -
.
9, -
, *
. ( ) > *
o n e p a iU |
. 10
NSError. P*
:

I
1

NSError

177

#import < F o u n d a tio n /F o u n d a tio n .h >


i n t main ( i n t a r g c , c o n s t c h a r * a r g v [ ] )
0 a u t o r e le a s e p o o l {

N S M u tab leS tring * s t r = [[N S M u ta b le S trin g a l l o c ] i n i t ] ;


f o r ( i n t i = 0 ; i < 10; i+ + ) {
[ s t r a p p e n d S tr in g :0 " A a r o n i s c o o l ! \ n " ] ;

>
// NSError
// . NSError
// .
NSError * e rro r = n i l ;

//

NSError NSString
BOOL success = [ s t r w riteT o F ile:g "/tm p /c o o l.tx t"

atomically:YES
encoding:NSUTF8StringEncoding
e rro r:& e rro r];
//
/ / NSError

i f (success) {
NSLog(0"done w ritin g /tm p /c o o l.tx t" );
} else {
N SLog(fw riting / t* p / c o o l.tx t f a ile d : %",
[e rro r lo c a liz e d D e sc rip tio n ]);

^,^*

>

>
return 0;

>

>-']-\ |

. ,
, @"/
too/darned/bad. txt".
.
: NSErw , NSError, .
? , .
, w rite T o F ile : atom ically : encoding: erro r:
* NSError
error. .
error .

178

23 NSStrlng NSData

NSError error (4$


, ,
, Q *
n
*
, * |
. (
NSError).
9, np#
: - ,
( ) .
, , .
,
.
NSString, writeToFile;
atom ically:encoding:error::
- (BOOL)writeToFile:(NSString *)path
atom ically:(B O O L )useA uxiliaryF ile
encoding:(N SStringEncoding)enc
erro r:(N S E rro r * * )e rro r

.
NSError.
, NSError , ,
, . ,
N0. NSError,
; NSError
, .

NSString
:
#import <Foundation/Foundation.h>
in t main ( in t argc, const char * argv[])

@autoreleasepool {

NSError * e r r o r = n i l ;
NSString * s t r = [ [N SString a llo c J
in itW ith C o n te n ts O fF ile :0 " /e tc /re s o lv . conf"
encoding : NSASCIIStringEncoding

error:& error];

NSData
if

(!str)

17

NSLog(0"read fa ile d : %@", [error lo calizedD escription l)j


} else {
NSLog(f"resolv.conf looks lik e t h is : %", s tr)j

>
>

return 0;

>

NSData
NSData . ,
URL- NSData,
. Foundation
ImageFetch;
Google NSData. NSData
:
#import <Foundation/Foundation. h>
int main (int argc, const char * a rg v[])

,^ :^ H

0autoreleasepool {
NSURL *url = [NSURL URLWithString:
0"http://www.google. com/images/logos/ps_logo2. png" ];
NSURLRequest *request = [NSURLRequest requestM ithU R L:url];
NSError *error = n i l ;
NSData *data * [NSURLConnection sendSynchronousRequest:request
returningResponse:NULL
e r r o r :& e r r o r ] ;
if(!data){
NSLog(f"fetch f a ile d : X j [ e r r o r lo c a liz e d D e s c rip tio n ] ) ;
return 1;

>
NSLog(fThe f i l e i s Xlu b y te s ", [data le n g th ]) ;
BOOL written [data w riteToFile:# "/tm p/google.png"
o p tio n s:0
e r r o r :& e r ro r ] ;

&

180

23 NSString NSData

i f ( lw r it t e n ) {
NSLog(@"write f a ile d : %0", [ localizedDescription]).
re tu rn 1;

>
NSLog(0"Successl");

>
re tu r n 0;

>
.
Preview.
w r i t e T o F i l e : o p t i o n s : e r r o r : , . NSDataWritingAtomic. , ,
.
. .
, , ,
. :
NSLog(@"The f i l e i s %lu b y te s " , [d a ta le n g t h ] ) ;
BOOL w ritte n = [data w riteToFile:@ "/tm p/google.png"
o p tio n s : NSDataWritingAtomic
e r ro r :& e r r o r ] j
i f (!w r itte n ) {
NSLog(@"write f a i l e d : %@", [ e r r o r lo calized D escrip tio n ]);
re tu rn 1;

>
,
.
, .

NSData
NSData .
:
#import <Foundation/Foundation.h>
in t main (in t argc, const char * argv[])

NSData

i8 i

g au toreleasep oo l {
NSURL * u rl = [NSURL URLW ithString:
@" h t t p : / /www. g o o g le . com/ im ages/ logos/ps_logo2. png" ];
NSURLRequest * re q u e s t = [NSURLRequest requestWithURL:url];
NSError * e rro r;
// ,

NSData * d a ta = [NSURLConnection sendSynchronousRequest:request


re tu rn in g R e sp o n se :NULL
e rro r:& e rro r];
i f (!d a ta ) {
NSLog(@"fetch f a i l e d : %@", [ e r r o r localizedD escription]);
r e tu r n 1;
>
NSLog(0"The f i l e i s %lu b y te s " , [d a ta le n g th ]);
BOOL w r itte n = [ d a ta w riteT oF ile:@ "/tm p/google.png"
o p ti o n s : NSDataWritingAtomic
e r r o r :& e r r o r ] ;
i f (!w ritte n ) {
NSLog(@w r ite f a i l e d : %@", [ e r r o r localizedD escription]);
r e tu r n 1;
}
NSLog(0"Success! " ) ;
NSData *readData
[NSData dataWithContentsOfFile:0"/tmp/google. png"];
NSLog(0'*The f i l e read from the d isk has %lu bytes",
[readData le n g th ]);

>
rtturn 0 :

>
<*. .

^0l^b. ^0^

\^^

^SSiBm

^^^^^^^

.
Foundat ion (, NSString NSArray)
.
.
,
, , . .
,
, , ,
. Mac OS iOS
NSRunLoop. , *
.
, , *
. Objective-C J
. ( ' j
X*,
.)

/: .* <1"J
X,
^.
, , . <(
.
<3a^ I
:
^I
, ,
- , . ( I! "0^ ^ I
25.)
I
.

4TPwgj>-L*%^Y^^^-

'^ ^ -^ - ^
-, , -----
: * -^* * * ^

X, onoMr*Ki
.
* i n * J
,

/
, /* n
, . 1!< nrtt^nm

m

,

24.1. Logger NSFimer

Xcode : Foundation
Callbacks.
. main.m:
#import < F o u n d a tio n /F o u n d a tio n .h >
in t main ( i n t a r g c , c o n s t c h a r * a r g v [ ] )

{
@ a u to rele ase p o o l {
[[NSRunLoop currentR unL oop] r u n ];

>
r e tu r n 0 ;
i

184

24

. : run
. , ,
- . ,
( Product Stop.)
,
. : Objective-C Logger
NSObject. (
File New New File...) Logger.h :
#import <Foundation/Foundation.h>
$in terface logger : NSObject
- (void)sayOuch:(NSTimer * ) t ;
0 end

,
. .
Logger.m sayOuch::
#import "Logger.h"
^implementation Logger
~ (void)sayOuch:(NSTimer * ) t
{
NSLog(0"Ouch!");
>
9

end

ciasa taw~~

foo?

foo? [

,'''~~ *

\ {
'\ \

fr**o"

__ I

1ini wofahUnKilo
jlloat he^htlnMewre____J
j-~(Houl)bodyMaeslndexJ

\ CtWP*-rM
e ."' ^^f"
^ 4qfeo?.
tmpioyM

Utoo]

C
T *F =
wetylnlnKtom M
1.1
omptoywtDmII

i
Employe*
Int employeeID

. 24.2.

185

.
, ,
.
, - : ,
.
, , .
(
) .

.
.
1923912?

^ -

NSObject


<

\ Cqqep 1923912? j^.......ftiw


\

/'

^ , int welghtlnKllo
j float heightInMeters
he&
J
(fioat)bodyMassTndex ]
>- (floaty

'V

4 *****?

Employee

[*foo]

[1&2...........
3912?

Pq:

is a =
..........
weightInKilos = 96
hefehtlnMeters * 1.{
employeelD = 15

Employee
* int emptoyeelD

. 24.3.

, ,
&. , sayOuch: Logger, .
0selector.
main.m Logger
NSTimer. sayOuch:.
#import <Foundation/Foundation.h>

#import "Logger.h"
int main ( in t argc, const char * argv[])
#autoreleasepool {

186

24
Logger *logger = [[Logger a llo c ] i n i t ] j
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval*2a

target:logger

s e le c to r :0selector(sayOuch:)
u serIn fo :n il
repeats:YES];
[[NSRunLoop currentRunLoop] run];

>
return 0;

>
. ( , .)
Ouch! .
: .
0selector(sayO uch) 3KBHBaneHTHa0selector(sayOuch:).
.
: timer, .
(, )
,
. __ unused.
.
__unused NSTimer * tim e r = [N S T im e r s c h e d u le d T im e r W ith T im e In te r v a l:2 .0
ta rg e t:lo g g e r
s e le c to r :@ s e le c to r ( s a y O u c h :)
u s e rIn fo :n il
r e p e a t s :YES];

. .


W0 *

. : ^ ^
. / . w >
( , | ^
/ . -
?
^
23 N SU R LC onnection * * :
-. , *^

187

> .
,

.
,
, - .
N SU R L C onnection .
, ,
, -
.
? NSURLConnection
. - ,
. ?
NSURLConnection ( ),
.
:
- (NSURLRequest * )c o n n e c tio n :(N S U R L C o n n e c tio n * )c
w illS e n d R e q u e st:(N S U R L R e q u e st * ) r e q
re d ire c tR e s p o n s e :(N S U R L R e s p o n s e * ) r e s ;
- (v o id )c o n n e c tio n :(N S U R L C o n n e c tio n * ) s e n d e r
d i d R e c e iv e A u th e n tic a ti o n C h a l le n g e : (NSURLAuthentication
C h a lle n g e * ) c h ;
! *m,;Hj
- (v o id )c o n n e c tio n :(N S U R L C o n n e c tio n * ) s e n d e r
d id R e c e iv e D a ta :(N S D a ta * ) d a t a ;
- (v o id )c o n n e c tio n D id F in ish L o a d in g :(N S U R L C o n n e c tio n * )sen d e rj
(v o id )c o n n ec tio n :(N S U R L C o n n ectio n * ) s e n d e r d id F ailW ith
E rr o r :(N S E rr o r * ) e r r o r ;
* (NSCachedURLResponse * )co n n ectio n :(N S U R L C o n n ectio n *)sender
w illC a c h e R e sp o n se : (NSCachedURLResponse *)cachedResponse;

, N S U R L C o n n e c tio n ,
NSTimer. ,
, N SU R LC onnection .
,> N SU R LC onnection ,
delegate.

188

24

. 24.4. Logger NSUrlCOnnection

main() NSURLConnection Logger


:

<Foundation/Foundation. h>
#import "Logger.h"
#im port

int main (int argc, const char * argv[])


{

@ autoreleasepool {

, i ''j * ^ E L J

Logger *logg er = [[L o g g e r a llo c ] i n i t ] ;


NSURL *url = [NSURL URLWithString:
0"http://www.gutenberg.org/cache/epub/205/pg205.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
__unused NSURLConnection *fetchConn

= [[NSURLConnection a llo c ] initWithRequest:request


d elegate:logger
startImmediately: Y ES ];
__unused

NSTimer *tim e r
= [NSTimer scheduledT im erW ithT im eInterval:2.0
ta rg e t:lo g g e r
s e le c to r:0 s e le c to r(s a y O u c h :)
userI n f o : n i l
repeats:YES];

[[NSRunLoop currentRunLoop] run]j

189

return 0;

>
L o g g er N SM utableD ata
.
Loggerk
| I ; _.g |
#import < F o u n d atio n /F o u n d atio n . h>
0 interface Logger : NSObject {

NSMutableData *incomingData;
}
- (void)sayOuch:(NSTimer * ) t ;
0end

L ogger.m :
#import "Logger.h"
^implementation Logger
- (void)sayOuch:(NSTimer * ) t
{
NSLog(@"Ouch!");
}

/ /
- (void)connection:(NSURLConnection *)connection
d id R eceiv eD ata:(N S D ata * ) d a t a

NSLog(0"received %lu b ytes" , [data le n g th ]);


/ / ,
i f (!incomingData) {
incomingData = [[NSMutableData a llo c ] i n i t ] ;
>
[incomingData appendData:data];
>

//
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

NSLog(0"Got i t a l l !");
>
NSString *string n [[NSString a llo c ] initWithData:incomingData
encoding:NSUTF8StringEncoding];
incomingData * n il;
NSLog(f"string has %lu ch aracters" , [ s tr in g le n g th ]);
/ / ,
/ / NSLog(0"The whole str in g i s %", s t r in g );
)

190

24

/ /
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error

{
NSLog(0"connection fa ile d : %@", [error localizedDescription])*
incomingData = n il;

>
0end

: ,
.
. ,
- . .
, : Apple
/.
Apple . (
.) .
?

Mac ,


. NSSys
t e m T im e Z o n e D id C h a n g e N o tif ic a tio n , >
.
main.m, Logge^
:

#import < F o u n d a tio n /F o u n d atio n .h >


# im p o rt "L o g g er.h "

int main (in t a rg c , c o n s t c h a r * a r g v [ ] )

@au to r e le a sepoo1 {
Logger * lo g g er - [[L ogger a l l o c ] i n i t ] ;
[ [N S N o tific a tio n C e n te r d e f a u ltC e n te r ]

191

addO bserver:logger

s e le c to r :0selector(zoneChange:)
name: NSSystemT imeZoneDidChangeNotification
o b je c t:n ll];
NSURL *url = [NSURL URLWithString:
@"http f //www. g u ten b erg I org/cache/epub/205/pg205.txt" ];
NSURLRequest * req u est = [NSURLRequest requestWithURL:url];

* .

unused NSURLConnection *fetchConn

* [[NSURLConnection a llo c ]
in itW ith R e q u e s t: req u est
d e le g a te :lo g g e r
startIm m ediately:Y E S ];
_unused NSTimer * tim er
= [NSTimer scheduledTim erW ithTim eInterval:2.0
ta r g e t: l o g g e r
sele c to r:@ se le c to r(say O u ch :)
u s e rIn fo :n il
rep eats:Y E S ]j

'
!
>!
iBOBQM

[[NSRunLoop currentR unLoop] ru n ];

>
return 0 ;

Logger.m\
- (void)zoneChange:(NSNotification *)note

c6 # H
y

NSLog(0"The system tim e zone has changed!");


}


. ,
zoneChange:. (
; .)

0?
B:,

" .
Apple >
' ?

192

24

, - ( NSTimer),
/ .
4
^l
( NSURLConnectio i *?
. I *
.
,
( , NSTimeZone), .


, ,
, ,
- , :
.
,
dealloc:
- (void )d ealloc

[[NSNotificationCenter defaultCenter]

r e m o v e O b s e r v e r :s e lf];

>
.
, ,
dealloc:
- (void)dealloc

{
[windowThatBossesM eAround s e t D e le g a t e : n i l ] j
[ta b le V ie w T h a tB e g s F o rD a ta s e tD a ta S o u r c e : n i l ] ;

>
. , ^
,
d ealloc:
- (void)dealloc

{
[buttonThatKeepsSendingM eM essages s e t T a r g e t : n i l ] ;
>

193

, Logger
. ( ,
: NSURLConnection
, a NSTimer .)

, .
- : , , , .
:
. ,
N S M utableA rray,
.
,
.
- .
, . |
? i
@ p ro to co l.
UITableView
..... ' --**'" ~ ~ ~ . - - . i - ~ ^ ~ ~ ~ ^ ~ -

Joe Conway
Mark Fenoglio

Brian Hardy

d a ta S o u rce

TerrlficVlawControtle^.

---------------- -----------------------------
* H
k MH l A
fW Mt
r ni lW
U M*

Scott nttehto
A le x

S H v en rm n

. 25.1. UITableView

195

, i O S
UITableView. UITableView ,
; .
: ,
.
, UIT ableView,
UITableV iew ? .
, .
,
.
UITableView UITableViewDataSource ( ):
/ / > > .
/ / NSObject
@protocol U IT ableV iew D ataSource <NSObject>

/ /
/ /
0required

/ / ,
/ /
- (N S In teger)tab leV iew :(U IT ab leV iew * ) t v numberOfRowsIn
S e c t i o n : (N S I n te g e r )s e c tio n ;

^ :/ '^ .^ ^ ^ . ;> ^ -

/ / ( ;
- (UITableViewCell *)tab leV iew :(U IT ab leV iew * )tv
cellForR ow A tIndexPath:(N SIndexPath * )ip ;

/ / ( )
/ /
@optional

/ / ,
/ /
(NSInteger)numberOfSectionsInTableView:(UITableView *)tv;

/ /
(BOOL)tableView:(UITableView * ) t v
(NSIndexPath * )ip ;
(BOOL)tableView:(UITableView * ) t v
(NSIndexPath * )ip ;

^ (void)tableView:(UITableView * )tv

c a n E d itR o w A tIn d e x P a th :

c a n M o v e R o w A tIn d e x P a th :

^6^

196

25

com m itE ditingStyle:(U IT ableV iew C ellE ditingStyle)editingStyle


forRowAtIndexPath:(NSIndexPath * )ip ;
- (void)tableV iew :(U ITableV iew * )tv
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)d estin ation In d exP ath;
/ /
/ / .
@end

, , E
Apple,
.
,
UITableView, :
U IT ableV iew D ataSource.
:
@ in te rfa c e T e r r if ic V ie w C o n tr o lle r
< U IT a b le V ie w D a ta S o u rc e >

: U IV ie w C o n tro lle r

end

, T e r r i f i c V i e w C o n t r o l l e r UIViewController,
U IT ableV iew D ataS ource.
,
:
@ in te r f a c e T e r r i f i c V i e w C o n t r o l l e r : U IV ie w C o n tro lle r
< U I T a b le V ie w D a ta S o u r c e , U I T a b le V ie w D e le g a te , U IT ex tF ield D eleg ate>

TerrificController.m .
, .
*
.
.
: C allb ack s 24 Logg6
NSURLConnection. Logge?-h
, Logger .
NSUR
C o n n e c t i o n . , . (
Callbacks 1*
N S U R L C o n n e c t i o n D e l e g a t e , ,/3*
.)

,* ;

, ,
. ,
. ,
,
. Objec
tive .
:
NSArray
NSDictionary
NSString
NSData
NSDate
NSNumber (, )
,
.
. Xcode
: F o u n d atio n
s to c k z. :
#im port < F o u n d a t io n /F o u n d a t io n .h >
in t m a in ( in t a r g c ,

const char * a r g v [])

@ a u to re le a s e p o o l {

NSMutableArray *stocks [[NSMutableArray alloc] in itjj


NSMutableDictionary *stock;
J

198

26
stock = [NSMutableDictionary d ictio n a ry ];
[stock setObject:0"AAPL"
forKey: " symbol"];
[ stock setO b ject: [NSNumber numberWithInt:200]
forKey: Q " shares"];
[stock s addObject:stock];
stock * [NSMutableDictionary d ictio n a ry ];
[stock setObject:0"GOOG"
forKey:"symbol"];
[ stock setO b ject: [NSNumber numberWithInt:160]
forKey:0"shares"];
[stock s addObject:stock];
[stock s w riteT oF ile:0" /tm p /stock s.p list"
atomically:YES];

>
return 0 ;
>
( sto c k .
, .)

. 26.1.

stocks.plist. 0
, :
<? xm l v e r s io n = " 1 . 0 " e n c o d in g = " U T F - 8 "?>
< !DOCTYPE p l i s t PUBLIC
" I / / A p p l e / /D TD P L IS T 1 . 0 / / E N " " h t t p : //w w w .a p p le .c o m /D T O s /
P r o p e r ty L is t-1 .0 .d td " >

199

< p list version="l.0">


<array>
<dict>
<key>shares</key>

<integer>200</integer>
<key>symbol</key>

<string>AAPL</string>
< /d ic t>
<dict>
< key>shares</key>
< in te g e r> 1 6 0 < /in te g e r>
<key>symbol</key>
<string>G O O G </string>
< /d ic t>
</array>
< /p lis t>

, ? XML. . .
, ,
Xcode
.
:
in t m ain (in t a rg c , c o n s t ch ar * a r g v [ ] )
{
@ autoreleasepool {
NSMutableArray * sto c k s = [[NSMutableArray alloc] i n i t J ;
N SM utableD ictionary * sto c k ;
stock = [N SM utableD ictionary d ic tio n a ry ];
[sto ck setObject:@"AAPL"
fo rK ey :@"symbol" ];
[sto ck setO bject:[N SN um ber n u m b e r W ith I n t:2 0 0 j
forK ey:@ "shares"J;
[sto c k s a d d O b je c t:sto c k ];
stock = [N SM utableD ictionary d ic tio n a ry ];
[sto ck setObject:0"GOOG"
forK ey: @*symbol" ];
[stock s e tO b je c t: [N SN um ber n u m b e r W ith I n t:1 6 0 ]
forKey:@"shares"];

[stocks a d d O b je c t:sto c k ];
[ stocks w rite T o F ile :@/tm p /s to c k s . p lis t"
atom ically:Y ESJ;

200

26

NSArray * s to c k L is t =
(N SA rray a r r a y W ith C o n te n ts O f F ile :0 " /tm p /s to c k s .p lis t" ] .
f o r (N S D ic tio n a ry *d i n s t o c k L i s t ) {
NSLog(@"I h av e %@ s h a r e s o f %@",
[d o b je c t F o r K e y : 0 " s h a r e s " ] ,
[d o b je c tF o r K e y :0 " s y m b o l" ] ) ;

>
>
return 0 ;
}
.

, 8 ,
, , , , , , ,
.

, ^ ^ ^ * " ^ , m a
iOS Cocoa.
^
o . ^ * ,
(GUI, Graphical User Interface),
? ,

r , *
,
,
, . ^
0,
.
. ; , p
._/1
i O S ,

Cocoa. Cocoa ,
^^^ __ p oUndation. Cocoa
I Mac.
_ , FoundaI Cocoa Touch
I tion.


iOS

iO S :
iT a h D o o d le , .
iT a h D o o d le .

f {j ype a' task S<tp Snsert

1 | insert )

Walk the dog


Get oil changed
Wrangle some cows

. 27.1. iTahDoodle

iO S , MHKffi
^
_
. , - ^
,
(, ) ( ,
).

iTahDoodle
I xcode File New N ew Pro}ect.... iOS (
MacOSX!) Application.
Empty Application.
Choose a template for your new project:
I

| ;

Fnmework U brary j
Other
fcM a cO S X

Master~DetaH
A p p lica tio n

O p e n G l Game


*^'

Page~8ased
Application

Sfog!e Vlew
Application

AppHcation
Fraroework & Ubrary
AppT<catton Ptug~in

I ****| i
aa tI
i'; *

V i
i< S J

1*
.* t
1'-b....4
i
*t|

System Plug-In

<M*er

Tabbed A p p lica tio n

U tility A p p lica tio n

Empty Application
T his tem plate pro vid es a startin g point fo r any application, it provides just an appfication
delegate and a w indow .

Cancel

I Previous !

Nexl - j

. 2 7 .2 . iOS

X c o d e .
, . . X c o d e
, , .
Xcode; ,
,
. 27.2.
. .
,
Big N e rd R a n c h forums.bignerdranch.com.
1^ Next iT ahD oodle. Com pany Identifier Bundle Identifier -

204

27 iOS

App Store.
. , BigNerd Ranch *
Company Identifier com.bignerdranch.
Choose options fo r your new project:

I.i fTahDoodJe
-
--
- -

----------}
--

.........- -...........

com .bignerdranch
com .bjgnerdranchJTahDoodte
O a ss Preftx
Devtce

8NR

Family '; iPhone


O Use Core Data
0

Use Autom atic Reference Counting

f ; Include U nitT ests

Cancel

Previous

. 27.3. iTahDoodle

C l a s s P r e f i x
, . ( .
) , OTl
Apple . ( BNR,
.)
^
Apple. ^
Apple, , NS coKpaw
*NeXTSTEP* (, *1**
-
]
Foundation).
UIKit, UI
, iT a h D o o d le ^
iPhone ( iPad
iT a h D o o d le ,
Core Data .

BNRAppDelegate

205

BNRAppDelegate
Empty A p p licatio n , Xcode
: BNRAppDelegate.
;
iOS. BNRAppDelegate ,

.
BNRAppDelegate.h.
.
,
, ,
.
.
.
#im port < U I K it/U I K it.h >
@ in terface BN R A ppD elegate : U IR e sp o n d e r
< U IA p p lic a tio n D e le g a te >

{
U ITableV iew * t a s k T a b l e ;
U IT e x tF ie ld * t a s k F i e l d ;
U IB utton * i n s e r t B u t t o n ;
N SM utableA rray * t a s k s ;

}
- (v o id )a d d T a s k :(id )s e n d e r;
@property ( s t r o n g , n o n a to m ic ) UIWindow *window;

@end

: UIKit.h. U IK it
iOS, U IT ableV iew , U IT extF ield
I UIButton. , BNRAppDelegate U IA pplicatip n D e le g a te .
, Foundation.h.
NSMutableArray? Foundation
8 ,
Foundation . ( ?
,( iTahf)oodle-I*refix.pch Supporting F iles
.)

206

27 tOS

I/


, ^ 1
iTahDoodle . 1
, . Objective-
,
Objective-C
.
iTahDoodle
XML. , - .
NSString.
,
BNRAppDelegate.h.
# im p o rt < U IK it/U IK it.h >

/ /
/ / ,
/ /
NSString *docPath(void);
@ in te rfa c e BNRAppDelegate : U IR esp o n d er
< U IA p p lic a tio n D e le g a te >

{
U ITableV iew * ta s k T a b le ;
U IT e x tF ie ld * t a s k F i e l d ;
U IB u tto n * in s e r t B u t t o n ;
N SM utableA rray * ta s k s ;

>
- ( v o id ) a d d T a s k :( id ) s e n d e r ;
@ property ( s t r o n g , n o n ato m ic) UIWindow *window;
@end

. , d o c P a t h ( ) ^
BNRAppDelegate.h, . ,
.
iT a h D o o d le .
iT a h D o o d le , 01

\TahDoodte

207

BNRAppDelegate.m .
, d o c P ath () , #im port, implementation (
).
#import "BNRAppDelegate.h"
/ / ,
/ /
N SString * d o c P a th ( )

{
NSArray * p a t h L i s t =
N SS earchPathF orD irectoriesInD om ains(N S D ocum entD irectory,
N SU serD om ainM ask, YES);
re tu rn [ [ p a th L is t o b je c tA tIn d e x :0 ]
s t rin g B y A p p e n d in g P a th C o m p o n e n t: 0 " d a ta . td " ];

>
^ im p le m e n ta tio n

docP ath() , NSSearchPathForDirectoriesInDomains ( ) . ,


, .
: iOS, - ,

. ( , NSSearchPathForDirectoriesInDomains ( ) , Foundation
Functions Reference .)

iTahDoodle
. , iT ah D o o d le : BNRAppDelegate,
: UITableView, UITextField,
UIButton N S M u ta b le A rra y .
-0 .

208

27 iOS

. 27.4. iTahDoodle

--
--, MVC (M odel-V iew -C ontroller),
: ,
.
:

.
;
. N S S tr in g , N S D ate N S A rra y
. iT a h D o o d le
N S M u ta b le A rra y , . 0*
N S S tr in g ,
.

.

. , ^
, .
UIView , ^
U IW indow . i T a h D o o d l e
U IT a b le V ie w , U IT e x tV ie w U I B u tto n . 1

'

--

209

: - , ,
.
,
.
.

.
iTahDoodle BNRAppDelegate,
,
,
.
. 27.5
(, ).
:
; ,
.
v

V
"

*

,

. 27.5. MVC


Cocoa Cocoa Touch
^an MVC
^,
^PDeie^at* ^ , BNR-

27 iOS

210


i O S , ^
. UIApplication, .

BNRAppDelegate,
UIApplication ( ).

. , UIApplicationoT application:didFinishLaunchingW ith
O p tio n s: . . ,
,
.
iTahD oodle , , .
BNRAppDelegate.m application:
d id F in ish L au n ch in g W ith O p tio n s:.
:
#pragma mark - Application delegate callbacks
- (B O O L)application:(U IA pplication * )a p p lic a tio n
didFinishLaunchingW ithOptions: (N SD ictionary *)launchO ptions

{
/ /
/ / , .
NSArray * p lis t = [NSArray arrayW ithC ontentsO fFile:docPath()]j

i f ( p lis t ) {
/ / ,
/ / ,
task s = [ p l i s t mutableCopy];
> e ls e {

/ / tasks [[NSMutableArray a llo c] in it ] ;

>

>

#pragma mark ? Objective-C 1


, X c tx le ix m '^
o e e . 1
BNKA,ppUelef^ate.m, ( , ^ ^
m entation AppDelegate, * *

211

.) ; Xcode
. ,
.
pragma mark. 6,
.


,
; , . ,
? ,
.
iTahDoodle applic
ation: didFin is hLaunhingWit hO ptions:. , .
, .
, iOS.
. ,
, .
, ,
.
*pragma mark - Application delegate callbacks
(BOOL)application:(UIApplication * )a p p lic a tio n
didFinishLaunchingWithOptions: (NSDictionary *)launchOptions

/ /
/ / , .
NSArray * p lis t = [NSArray arrayWithContentsOfFile:docPath()];
i f (p lis t) {

/ / ,
/ / .
tasks = [ p l i s t mutableCopy];
> else {

/ / ,
tasks [[N S M u ta b le A rra y a llo cJ init];

/ / UIWlndow.

27 iOS

/ / CGRect
/ / ( >) (w id th ,h eig h t)
CGRect windowFrame = [[UIScreen mainScreen] bounds];
UIWindow *theMindow = [[UIUindow a llo c ] initWithFrame:windowFramej.
[ s e l f setWindow:theWindow];
/ /
/ / .
/ / CGRectMake() CGRect
(x , , width, h eigh t)
CGRect tableFrame = CGRectMake(0, 80, 320, 380);
CGRect fieldFrame - CGRectMake(20, 40, 200, 31);
CGRect buttonFrame = CGRectMake(228, 40, 72, 31);
/ /
taskTable = [[UITableView a llo c ] initWithFrame:tableFrame
s t y l e :UITableViewStylePlain];
[taskTable setS ep a ra to rS ty le: UITableViewCellSeparatorStyleNone];
/ /
taskF ield = [[U ITextField a llo c ] initWithFrame:fieldFrame];
[task F ield setBorderStyle:UITextBorderStyleRoundedRect];
[task F ield setPlaceholder:@"Type a ta sk , tap Insert"];
/ / In sert
/ / .
insertButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[insertB utton setFrame:buttonFrame];
/ /
/ / "/". In sert
/ / -addTask:
[insertButton addTarget:self
action:0selector(addT ask:)
forControlEvents:UIControlEventTouchUpInside];
/ /
[ insertButton s e t T it le :@"Insert"
forState:U IC ontrolStateN orm al];

/ /
[ [ s e l f window] addSubview:taskTable];
[ [ s e l f window] addSubview :taskField];
[ [ s e l f window] addSubview:insertButton];

/ /
[ [ s e l f w in d o w ] s e t B a c k g r o u n d C o lo r : [ u iC o l o r w h i t e C o l o r ] ] j

I
iOS Simulator

213

[ [ s e l f window] m a k eK ey A n d V isib le];


r e tu r n YES;

iOS Simulator
, ;
, . Xcode Scheme
Run. iPhone 5.X Simulator
iOS:
r
[ iTahDoodte >iPhone S.0 Simulator

-vW088^-

. 27.6. Scheme

. 27.7. iTahDoodle

214

27 iOS

.
, addTask: .
; addTask:.
C o c o a T o u c h
. ,
iO S .
, application:
didFinishL aunchingW ithO ptions:, . ,
Insert ,
addTask: . ( ,
.)


, ,
. ,
,
. ,
. iT a h D o o d le
B N R A p p D eleg ate.
BNRAppDelegate.m a p p l i c a t i o n : didFinishLaunch
i n g W i t h O p t i o n s : , cooonr
, B N R A p p D e le g a te :

/ /
taskTable = [[UITableView a llo c ] initWithFrame:tableFrame
style:UITableViewStylePlaiW
[taskTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];

/ /

[taskTable setD ataS ou rce:self];

/ /
taskField = [[UITextField a llo c ] initWithFrame:fieldFrame];

^^
Pa ^,
U IT a b le V ie w D a ta S o u rc e . L ^
BN R A ppD elegate

BNRAppDelegate.h:

~ ^ ij
^ i n t e r f a c e B N R A ppD elegate : U IR e s p o n d e r
< U I A p p lic a tio n D e le g a te , U IT a b le V ie w D a ta S o u rc e >

U IT ableV iew * t a s k T a b l e ;
U IT e x tF ie ld * t a s k F i e l d ;
U IB u tto n * i n s e r t B u t t o n ;
N SM utableA rray * t a s k s ;

>

- (v o id )a d d T a s k :(id )s e n d e r;

U IT a b le V ie w D a ta S o u rc e ,
BNRAppDelegate.

,
. co:
#pragma mark - T a b le V iew m an ag em en t
* ( N S I n te g e r ) ta b le V ie w :( U I T a b le V ie w * ) ta b le V ie w
n u m b e r O f R o w s I n S e c tio n :( N S I n te g e r ) s e c tio n

{
/ /
/ / ,
/ / t a s k s
r e tu r n [ t a s k s c o u n t ] ;

(U ITableV iew C ell * ) ta b le V ie w :( U I T a b le V ie w * )ta b le V ie w


c e llF o rR o w A tIn d e x P a th : (N S In d e x P a th * )in d e x P a th

//
//
//
//
//


, ,

,
. , ,
.

c^ * Tab leV iew C ell *c = [ t a s k T a b l e d e q u e u e R e u sa b le C e llW ith Id e n tifie r:0

if

) {
/ / ... ,
/ / .
* [[U IT a b leV ie w C ell

alloc]

i n l t U l t h S t y l e : U XTableViewCellStyleD efault
|

reuseIdentifier:"Cell"];
&

216

27 iOS

/ /
/ / ( todoItems)
NSString *item * [task s objectA tIndex:[indexPath row]];
[[c textL abel] setT ext:item ];
/ / and hand back to the ta b le view th e properly configured cell
return ;

. 27.8. iTahDoodle

,
a p p lic a tio n :d id F in is h L a u n c h in g W ith O p tio n s :.
- (B O O L )ap p lication :(U IA p p lication * ) a p p lic a t io n
didF inishL aunchingW ithO ptions: (N S D iction ary *)lau nchO p tions

{
/ /
/ / , .
NSArray * p l i s t = [NSArray arrayW ith C on ten tsO fF ile:d ocP ath ()];
i f (p lis t) {
/ / ,
/ / ,
ta sk s = [ p l i s t mutableCopy];
} e ls e {
/ / ,
ta sk s = [[NSMutableArray a l l o c ] i n i t ] j

>
/ / ta sk s ?
i f ([ta s k s count] 0) {

Put
[task s
[tasks
[tasks

||

217

some s t r in g s in i t
addObject:@"Malk th e dogs"];
addQbject :" Feed th e hogs"];
addObject:g"Chop th e lo g s" ];

>
/ / UIWindow
CGRect w indow Fram e [ [ U I S c r e e n m a in S c r e e n ] b o u n d s ];
UIWindow *theW indow = [[U IW in d o w a l l o c ] initW ithFram e:w indow Fram e];
[ s e l f se tW in d o w :th e W in d o w ];

>
.
, - .
!


U IButton a p p lication :d id F in ish L au n ch in gW ith O p tio
ns, /:
[ in s e r tB u tto n a d d T a r g e t : s e l f
a c tio n :@ s e le c to r(a d d T a s k :)
fo rC o n t r o l Ev e n t s : U I C o n tr o lE v e n tT o u c h U p I n s id e ] j

s e l f , addT ask:. , Insert BNRAppDelegate addTask:. ,


addTask: BNRAppDelegate.m.
j'.

'( v o i d ) a d d T a s k :( id ) s e n d e r

/ /
NSString * t = [ t a s k F i e l d t e x t ] ;
/ / , t a s k F i e l d
i* ( [ t is E q u a lT o S tr in g :0 " " ] ) {
r e tu r n ;

}
/ /
[task s a d d O b je c t:t] ;

/ / ,
[taskT abIe lo a d O a ta ];
/ /
[task F ie ld s e t T e x t : # " " ] ;

&

218

27 iOS
/ /
[taskField resignFirstResponder];

>
resig n F irstR esp o n d er?

, .
, ,
,
, ,
(, 3er1
).
,
, becomeF irstR esponder. , I
resignFirstResponder, P
|
.
b
(, )
, . -1
, , 9
. addTask: ^
,
.
fl<


00 I 'Q
fy

iTahDoodle . ,
, ,
.
C o c o a T o u c h |
, 0
U IA pplicationD elegate,4T o6bi 0
. BNRAppDelegate.m
, :
- ( v o id ) a p p lic a t io n D id E n t e r B a c k g r o u n d : ( U IA p p lic a tio n * ) a p p l i c a tin

{
//
//

iOS 4 .0 +
ta s k s

: mainQ?

219

[ta s k s w r i te T o F ile : d o c P a th ( ) a t o m i c a l l y : Y E S ] ;

>
I ( v o id ) a p p lic a tio n W illT e r m in a te :( U I A p p lic a tio n * ) a p p lic a tio n

/ / iOS 4.0
/ / tasks
[ta sk s w r i te T o F ile :d o c P a th ( ) atomically:YES];

}
'
*
'
''
.
fi I iO S .
, .

: main()?

O b j e c t iv e - C ,
main ( ) .
C o c o a / C o c o a T o u c h ,
Cocoa C ocoa T o u ch . ,
, main.m:
return U IA p p lic a tio n M a in (a rg c , a r g v , n i l ,
N S S trin g F ro m C la s s ( [BNRAppDelegate c l a s s ] ) ) ;

, . ?
UIApplicationMain() ,
.
U IA pp lication. ,
() , .
: ,
P , .
m a in ( ) application:didF inishL aunchingW ith
^ * io n s: .

f
j

T a h D o o d le Cocoa.
iT a h D o o d le ,
;
. iO S UIT ableView, UIT e x t F i e l d U IB u tto n .
N STableV iew , . N S B u tto n ,
.

NSWindow

NSTableColumn
NSTableView
NSScrollView

NSButton

. 2 8 . 1 . TahDoodle

BNRDocument.h

221

,
.
Interface Builder, Xcode, ,
.
X code File New New Project.... Mac OS X
Application. Cocoa
Application TahDoodle. TahDoodle
, cpa . Document Extension
, ( ) .
,
tdl. TahDoodle Core D ata
.

Choose options for your new project;

producttame

TahDoodle

mpanykfentifler \c o m .b ig n trd r*n c h

Bundle Identifier com.bJgnerdranch.TahDoodfe


OassPreflx pS3T
App Score Category

None

______ _____ _

g5} Create Document-Based Apphcat/on


Document Extenston tdl
Q Use Core Data
0 Include Unit Tests
Q indude SpotfJflht fmpoJter

( Previous ^) (

Next ^)

. 28.2. Cocoa

BNRDocument.h
, - BNRDocument.h, ha

*
4 *odoItems
w"a ~
^
, a itemTableView
itemT aoieview
^ m m r n todoItems.
BNRDocument NSTableViewDataSource.|

222

28

# im p o rt < C o co a/C o co a. h >


@ in te r f a c e BNROocument : NSDocument <N STableV iew D ataSource>

{
N S M utableA rray * to d o I te m s ;
I B O u tle t N STableV iew * ite m T a b le V ie w ;

>
- ( I B A c tio n ) c r e a te N e w I te m :( i d ) s e n d e r ;
* @end

: Insert . (
, .) -

createNewItem:.

, BNRAppDelegate. -
,
NSDocument. TahDoodle BNRDocument.
-
. , TahDoodle BNRDocument
( ).
, , tasks .
,
.

IBOutlet IBAction. Xcode: (IB O u tle t)*
(IBAction),
Interface Builder

Interface Builder
.1 ^0$I I
BNRDocumentJW
jcib (XML-*
face Builder), Interface Builder | |

( I
. NSWindow,
.
$' I
Xcode # ^ 0
Utilities. Utilities
, .

BNRDocument.xib

223


, .
Q +AQ | &
If OtrttaU

^ rffldth^

r*Hcioh!
5
w

M
^l^l^l4C
o^^w
T
<
^^^^H
w
^^ttim
^^^3W
sW
W
fiS3M
8S^R
SS^Sv^S^^^^vv^^A
'^^^A
\
11

... i ;MMmumSJr#

ControU0Ow

{*

,. :. ;.--: >4>wt4Qww^
mItleJf<mftespand*f
m#mi

, M vtnciAQ Qwtets
...........
tjffi5W....: . jH*'.l*HH
WsOwfflH
w

NiWR*fertncinj Outlcr

A0parua0Tkfetor

0 Ttxtur*d

VjUctivtdActtont

dcmtoiatttrizv:

ftQAboy* 1^ 1

makeKeyAndOrderffftm:

mloUtofizr

:fOywted TWt AndToritar

ard*r8 *ck
ordtrffom

| | foo%HurButton

fctator Q When Goscd

of<kfOur

Q Mt 0n0*

p*rformCtow
pwformMiniatorizr
perfbrm2 oom:

QvwbltAiUuncti
I Q Auto tookutetts Vtow Loop

print

Spacts toftnrtd fchavtor

runTootbtrCustomizatkMPitote

faport I *Hftntd B*havKH

togQftfuftScrMfl:
tog9 feT<xrfb*rSh0 wn:

CydMgl Mtrrtd tehavk>r

toBScrew Unwpporttd

I toftrrcd Sehavk>r
DcferTtd

0 Shot

~T\

f proportional Hofjzomai
1^poftiont| V*rtlcal
Content Border [ Autoiitt

&ufored

Manual

0
0
0
0
0
0
0
0
0
0
0
0
0

)
]

Bottom

Manual

28.3. ,
U t i l i t i e s , , ,

. ,
. , Interface
Builder, ,
.
.
^ble, . , Table View,
^ NSTableView. ,
].

1 BNRDocument.xib

^ NSTableView .
( *),1) , ,
.

224

28 Cocoa

fOtu* * * I C*<*U*------ -------------

01*"<0 ^
g | AuwesttesSub^twi

j C*n 0 19* CofKUTTtntty

1&:^^
I^j^i^
^*^** ?^^1~^^~jD

-^.-iSW^^^^aw^K^-yf>^j^yjW^^^*1
*="
'***|^
*""S
* "?'*
' * * V iw r - Dtepbyi rccord^ntflM
5

J JSnp d<u in Md *8 owi thc ottrto

S r ^ ^ * . *******to** aAd res&e*od .


,

Mw^wiewww^wwww^^wwwwwewwwAWwwwvwxmv^wwflwwxwwihttwxwww^wewRtWM<

j;_#c*w

lmag* * Text TaWe CtH VkwNSTabteCelfVicwis an HSVfcwth*


^ g * d m *f5TabteV*w 'msunct%to,.
Text T*M* Ccil Vtaw
^ . >

. 28.4. NSTableView
:
.

Human Interface Guidelines (HIG) *
Apple ,
Mac. 10
HIG iPhone iPad. H IG 01
.
^
. *
, &1
. N S T a b le V ie w *
, ,
: N S S c r o l l V i e w , NSTable ^
N S T a b le C o lu m n . #
, Control Shift Hi ^
. (
. N S T a b le V ie w .

B N R D ocum ent^^^

**$
,Window

Text Cell

Text Cell

lmm Window

f
N f NSWindow

Vicw

NSView

Scroll Vicw - Vfew

N5ScroltVfew
Vlcw
NSTableView

Cotumn

_J

NSTableCotomn

. 28.5.

,
. ,
.

TextC*ii

^^^1 !

' '

. 28.6.


0

| 0, (/) p
,
P*-

- .

226

28 Cocoa

Control Shift, NSScrollView .


qjS^,
. Autosizing.
|
, .
. ,
, ,
. NSScrollView
NSWindow.

I . *

. . ,
,
,
.

.

( )
.
| View

.^jHMifeMto

Show I Frame Rectangle


f

49

20 0

,_____ *

467|Q
Width

4 4 ]
Height

Origin

I
I||^I
I

5
*

I
Autosi1)n 9

Example

Arrange Position View

. 28.7.

|
^

BNRDocument.xib

227

.
. NSButton .
, ;

(Rounded Rect B utton). ,
;
.
In sert.
,
,
.

. 28.8. Insert
, ,
TahDoodle: N S T ableV iew N S B u tto n , . ,
.
.
N S B u tto n ,
,
:

[insertButton setT itle:0 " In sert"


for S ta te : U IC o n tr o lS ta te N o r m a l ];

Interface Builder,
?
^ 6oej. iTahDoodle
^ ,
Interface Builder.

228

28 Cocoa

f l|

:
*

T*hOoodH

,^T*WXxxa**

8roHapow*

1 i
utm
.*~. ***

*Mt^ejtf*^^iflbrieK8fttiai*i*Se*jti**__,^_

$ . ^9*. ) >^4

| !
^^

f * NRO<x u m # n t. < fb

Xtodt

& . t*hOeortto ^
|

T*hOoo<ite.*cod*prQi ~ -

^ *.*.._

TMWMtw

f W # '* O w n f f

*aW W A*OMMftM<*

$.

/
7Wt , |
yswe*
.

;'^G
tfwfbd**^
g j ^ --------- ^ t |

SHW*WC.1#
00
ttgUMteftUMl

!.0A*ftc*kt&
ffcvtab#
^ J te w e rtb *

Swm 'Mtfl*dtouMor
j tofcfffdM*riV

fctfS_JOdtaeiJetod
Mmiet0 u!#i*
!3122__ t'fi"Jj
IW?4*
W BH dHrtH W W fl^

M i * MtfMfb > .

Cmdtni fcrtw fotw****w*

ir:

flWfM0C<01Uf^W(AfKJdWfte4..
Rounded R*ct taROff - Mtnw

} mopmfow*WBBui *

_;rtWVH'lWWl*W*''^
j

(0 b u t t o n

.~ 'iL

. 28.9. BNRDocument.xib

Interface Builder
.
, /
.
\
(Placeho
. (docum ent outline). (&J
, 0 > 0
.)
^
P la c e h o ld e rs F i l e ' s Owner. ^
, ^^
, File* s Owner ,
^
. 43
Owner BNRDocument.
, Q^<
Insert Fw
Control.


, >i'n ii^w.>^ha^ ii. Ta.*i-..^.-^,.-: , ^^. , _

HiccboUkii

| Fll*4 Owrvtr
ftrtX Rt&pon<tar
dbAppHcatioft

Column
*ffT ScroHer
_ | ScroHer

| Header Vlew
^ * Pusb Button

~ _ ^

V|W

. 28.10.

n*ccMd*r&
^_ ^'<SK'owiy
jP First Reipo<uter""^"

^&
Objeeu
v^M m
v <; v^w
; Scrofl Vicw -

^TabteV*ew
^Scro#tr
ScwBtr
Tafcie Header Vkcw j

. 2 8 .1 1 .

229

23 0

28

,
. createN ew Item :
,
(. 28.12)
0 PUc*hokters

,: FUc4 Owner
First Responder

^^

r^ApphcatK>n

ftO b*ects

I Wmdow
I

ijV tew
f^ScrottView

iv?d Aaiofts
createNewKem
^
printDoeuroeni:
reveftDocumentToSaved
I
funPa9 eLay0 ut:
saveOocumem
saveDocumentAs:
saveDocumentT:
_____

Window

TaWeVtew

Scrotter
Header View

. 28.12.
/ .

"

iT a h D o o d le :

[in sertB u tton ad d T arget:self


a ction :@ selector(ad d T ask :)
forC ontrolE vents:UIControlEventTouchUpInside]J

fm

ic w
^ R
i vD
b /ocum
u L u i i ien
v i ^t.. -
- *
*
ite m T a b le. cVv ie
w r w ia^ c a uBiN
Control Files O w ner ( B N R D o c u fflfl*
NSTableView .
: ite m T a b le V ie w .
&?
, * ^
Control Shift, N STableV iew . ^ ,^c
Control File's Owner 8
dataSource.

ffiF NmfcoHt n

$*
RfSt*MPOf^Ww
4bAp0teHOft

0 Oty*cti

*fJ*todew
?ffcview
f Sonoil Vkw - * vta*

^Tsbk $
^Scro#er
^Scfoller
T*tofe Header Vttw
Pwb Button

&:fcmonCttt

. 28.13.

. 28.14. ,

232

28 Cocoa

, ?
BNRDocument NSTableV iew. Interface
Builder, NSTa
bleV iew , . ,
, d a ta S o u r c e .
In te rfa c e B u iId er, d a t a S o u r c e
BNRDocument.
iTahDoodle
[taskTable setD ataS ou rce:self];

I B O u t l e t I B A c t i o n ,
Interface Builder, :
IB, !
Interface Builder IBOutlet
I B A c tio n , .
I B O u t l e t I B A c ti o n :
#d efin e IBAction void
#d efin e IBOutlet

, # d e f i n e , ,
IB A c tio n v o id , ,
a I B O u t l e t . , I B O u tle t , IBAction
v o id , ,
, .
, XIB
, .
XIB .
, . .
,
. coo6ffl#1
BNRDocument, .
BNRDocument ,
.

MVC
, .
:

B N R D ocU m enfr^

233

NSButton
action = createNewltem

itemsTableView

dataSource

BNRDocument

NSMutableArray

. 2 8 .1 5 . TahDoodle

NSDocument , BNRDocument, -

. .
N S D o c u m e n t ,
, - . N S D o c u m e n t
,
. B N R D o cu m en t NRDocument
( NSMutableArray
N S S trin g ).

BNRDocument.m
,
, .
B N R D ocum ent.m ,
, c r e a t e N e w I te m :.
#import "BNRDocument.h"
^implementation BNRDocument
#pragma mark - NSDocument O verrides

^ (NSString *)windowNibName
return fl"BNRDocument";

234

28 Cocoa

>
#pragm a mark - A c tio n s
- (IB A c tio n ) c r e a te N e w Ite m :(id ) s e n d e r

{
/ /

i f ( ! to d o I te m s ) {
to d o Ite m s = [N SM utableA rray a r r a y ] ;

>
[to d o Ite m s addO bject:0"N ew Ite m ] ;
/ / -re lo a d D a ta
/ / (
/ / BNRDocument)
[item T ableV iew r e lo a d D a ta ] ;
/ / -updateC hangeC ount: ,
/ / . NSChangeDone
/ / .
[ s e l f updateC hangeC ount: NSChangeDone] ;

>

( NSTableViewDataSource):
#pragma mark Data Source Methods
- ( N S I n te g e r) n u m b e r O fR o w s In T a b le V ie w :( N S T a b le V ie w * ) t v

/ / todoIte*<
/ /
/ / ,
return [todoItem s count];

>
- (id )ta b leV iew :(NSTableView *)tableV iew
objectValueForTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row

/ / t o d o I t e m s , ,
//

return [todoItems objectAtIndex:row];

>
- (void)tabXeView:(NSTableView *)tableView

BNRDocument.m

235

s e tO b je c tV a lu e :( id ) o b j e c t
f o rT a b le C o lu m n : (N S T ab leC o lu m n * )tab leC o lu m n
r o w : ( N S I n te g e r ) r o w

/ / ,
/ / todoItem s
[todoItems replaceObjectAtIndex:row w ith O b je c t:o b je c t] j
/ /
.
[s e lf updateChangeCount:NSChangeDone];

}
. TahDoodle ,
.
: . , ,
OTNDocument BNRDocument:

- (NSData * ) d a t a O f T y p e : ( N S S t r i n g * )ty p eN am e
e r r o r :( N S E r r o r * * )o u tE rro r

{
/ / .
/ / NSData
/ / ,
/ / ,
i f (!todoItem s) {
todoItems * [NSMutableArray array];

>
/ / todoItem s NSData
NSData *data = [N SP rop ertyL istS erialization
d a t a W i t h P r o p e r t y L i s t :to d o Item s
f o r m a t : N SPropertyListX M LForm at_vl_0
o p tio n s :0
e r r o r : o u tE rro r];

/ / NSData
return data:

(BOOL)readFromData: (N S D ata * ) d a t a
o f T y p e :( N S S tr in g * )ty p eN am e
|
e rr o r:( N S E r ro r * * )o u tE rro r

/ / .
/ / NSData
// todoItems

_..,,*j?

236

28

to d o Ite m s [ N S P r o p e r t y L i s t S e r i a l i z a t i o n
p r o p e r ty L is tW ith D a t a :d a ta
o p t i o n s : N SP ropertyL istM utableC ontainers
form at:N U LL
e rro r:o u tE rro r];

/ /
/ /
r e tu r n (to d o Ite m s != n i l ) ;

}
: NSError**.
N S E rro r, propertyList
W ith D a ta : o p t i o n s : f o r m a t : e r r o r : ,
N S E rro r.
. .

' , ^ ^ ,, ^ ^
N S E r r o r
N S E rro r,
(


Objective-C
Objective-C ,
iOS Cocoa. ! ,
O bjective-C .

N SO bject i n i t .
i n i t , .
, a llo c , a i n i t .
i n i t :
N S M u tab le A rray * t h i n g s = [[N S M u ta b le A rra y a l l o c ]

in it];

, i n i t , .
NSObject. , .

init
: F o u n d a tio n ^
A ppliances. : AppliancenOwne P
p lia n c e ( A ppliance). A p p lia n c e ()
productName ( ) v o lta g e ().
OwnedAppliance : N SO bject Appliance. ^
Appliance.h ^
ductName v o lta g e :
# im p o r t < F o u n d a tio n /F o u n d a tio n .h >
@ i n te r f a c e A p p lia n c e : N S O b ject {

NSString *productName;
in t voltage;

>

0property (copy) NSString *productName;


0property in t voltag e;

0end

( copy 30.)
Appliance

, )nt voltage
~
,
J NSString *productName |
-init
|-initWithProductName:

\
J

................. .................

p ~ ~ * 2 ~ * * ~ * ** ***?* ~ **-
i
OwnedAppliance
^ ~ -~ -~ ~ ~ ~ ~ ~ ~ ~ -~ -~ ~ ~ ~ -~ -~ -'
i NSMutableSet *ownerNames
%*m~,m~ i ~ ~ ~ ~ ' ... - i.i . . J

] -frMtVWthProductName:
*-initWithProductName1irstOwnerName:

J * * 4**. - - ~ * - - - *- - -

----- * ------. --------* I

. 29.1. Appliance OwnedAppliance


Appliance.m
:
#im port " A p p lia n c e .h "
# im p le m e n ta tio n A p p l i a n c e

#synthesize productName, v o lta g e ;

A p p l i a n c e :
A ppliance *a [ [ A p p l i a n c e a l l o c ]

in it];

A p p l i a n c e i n i t , i n i t ,
N S O b je c t. , ,
A p p l i a n c e , .
ProductName A p p l i a n c e n i l , v o lt *8* .

" init
p tf KO, J^ WX
> .

, .
jH
, A p p lia n c e v o lta g e
120. Appliance.m -1
i n i t , i n i t NSObject.
- (id )in it

{
/ / i n i t NSObject
s e l f = [super i n i t ] ;
/ / v o ltage
v o lta g e = 120;
/ / ob ject
return s e l f ;

>
A p p lian ce voltageno
120. (,
. ,
,
s e tV o lta g e :.)
i n i t ;
, ,
.
. init.
:

i n i t - ,
, .

i n i t ,
n il .

Apple , s e l f
, i n i t .
i n i t .
A pple ,
, n il. -

i n i t Apple:
- (id )in it

{
/ / i n i t N S O b ject

self [super i n l t J ;

// , nil?
i f (s e lf) {

// voltage
voltage = 120;

}
return s e lf;

, , O bjective-C
. ,
Apple i n i t .


i n i t A p p lia n c e ,
, .
i n i t ,
. i n i t :

30

- (id)init
j#

{
/ / i n i t N S O b je c t
s e lf = [s u p e r i n i t ] ;
/ / , n i l ?
if (s e lf) {

4>\

/ / v o l t a g e
[ s e lf s e tV o lta g e :1 2 0 ];

>
re tu rn s e l f ;

^ -

| . :
i n i t ! %^ ^ ,
I ^ i n i t . :
vf' P 1}. .

, . *
^
.

init

, . ,
Appliance (n il ).
- ,
.
i n i t , i n i t .
, .
Appliance :
Appliance *a = [[A ppliance a llo c ] initWithProductName:@"Toaster"];

in itW ith P r o d u c tN a m e : -
N S S tr in g . Appliance.h:
#import <Foundation/Foundation.h>
@interface Appliance : NSObject {
NSString *productName;
in t voltage;

>

@property (copy) NSString *productName;


@property in t voltage;
- (id)initWithProductName:(NSString *)pn;
@end
Appliance.m i n i t .
ProductName: productName, .

(id)initMithProductName:(NSString *)pn

/ / in it NSObject
s e lf = [super in it ] ;
/ / , n il?
i f (s e lf ) {

4^jth'
i<1
.

//
[se lf setProductName:pn];
// voltaee
[self setVoltage: 120 ];
}
return s e lf;

,
.
Appliance .
Appliance.h Appliance.m ,
, initWithProductName:. ,
A p p lia n c e ?
Appliance *a = [[Appliance a llo c ] i n i t ] ;

. ,
Appliance NSObject , NSObject. NSObject init.
,
A p p lia n c e nil
v o lta g e . ,
Application voltage, 120,
, n i l . ?
: Appliance.m init,
initW ithProductNam e : .
* (id)init
{
return [self initWithProductName:0"Unknown"];
>

i n i t initWithrductName:, .
description.
Appliance.m:
* (NSString *)description
return [NSString stringWithFormat:0"<%0: %
d volts>", productNae,
voltage];

main.m\
#import <Foundation/Foundation.h>
#import "Appliance.h"
in t main (in t argc, const char * argv[])
{
@autoreleasepool {
Appliance *a = [[Appliance a llo c ] i n i t ] ;
NSLog(#"a is %0", a);
[a setProductName:0"Washing Machine"];
[a setVoltage:240];
NSLog(0"a is%0"> a);
>
return 0 ;
>

.
. - cy6
A p p lia n c e OwnedAppliance.
Choose options for your new flte:

C c*nc<l )
. 29.2. Appiiance

init

245

O w n e d A p p lia n c e .h
.
#import "A ppliance.h"
#interface OwnedAppliance : Appliance {
NSMutableSet *ownerNames;
>
(id)initW ithProductNam e:(NSString *)pn
firstOwnerNam e:(NSString *)n;
- (void)addOwnerNamesObject:(NSString *)n;
- (void)removeOwnerNamesObject:(NSString *)n;
#end

,
OwnedAppliance.m :
#import "OwnedAppliance.h"
#implementation OwnedAppliance
- (id)initMithProductNam e:(NSString *)pn
firstOwnerName:(NSString *)n
{
//
se lf = [super initW ithProductName:pn];
i f (se lf) {
//
ownerNames = [[NSMutableSet a llo c ] in it ] ;
// n il?
i f (n) {
[ownerNames addObject:n ];
>
>
//
return s e lf;
>

(void)removeOwnerNamesObject: (NSString *)n

# *

246

29 init

{
[ownerNames removeObject:n];
>
@end

: v o lta g e productNa*
initW ithProductNam e: Appliance.
,
, ; ,
, .
, Appliance i n i t . -
, :
OwnedAppliance *a = [[OwnedAppliance a llo c ] initWithProductName:0"Toast
e r"];

initWithProductName:
Appliance. ownerNames, ,
ownerNames
OwnedAppliance.
.
OwnedAppliance.m in itW ith P r o d u ct
Name:, initWithProductName:firstOwnerName:
firstOwnerName.
- (id)initWithProductName:(NSString *)pn

return [ s e lf initWithProductName:pn firstOwnerName:nil];

>

: i n i t OwnedApplianC
. :
OwnedAppliance *a = [[OwnedAppliance a llo c ] in it ] ;

? i n i t OwnedAppl*anC
i n i t
[ s e l f initW ithProductNam e:@ "Unknow n"]. se lf r $
OwnedAppliance, i n i t W i t h P r o d u c t N a
OwnedAppliance, [ s e l f initWithProductNan>6,
firstO w nerNam e:nil].

, ^
.

. 29.3
*
^
^*^
^
f*MfnJ^
. , init
NSObject, initWithProductNaee: A p p lia n ce , a in itW ith P rod u ctN am e : firstOwnerName: ~
OwnedAppliance. .
,
( ) .
,
( Appliance OwnedAp
pliance),
. Appliance.k
#import < F o u n d a tio n /F o u n d a tio n .h >
@ interface A p p lia n ce : NSObject {

NSString *productName;
int voltage;
}

0property (co p y ) N S S trin g *productName;


^property in t v o lt a g e ;
/ /
* (id )in itW ith P rod u ctN am e:(N S S trin g * )Pn*

0end

OwnedAppliance.h:
#import " A p p lia n c e .h "

#*0 *
^ interface Ow nedAppliance

: A p p lia n c e {

248

29 in it
NSMutableSet *ownerNames;

>
//
- (id)initWithProductName:(NSString *)pn
firstOwnerName:(NSString *)n;
- (void)addOwnerNamesObject:(NSString *)n;
- (void)removeOwnerNamesObject:(NSString *)n;

0 end

, , Objective-C :
,
.
. ( ).

.

,
,
.
,
, .

init
, #
.
NSObject WallSafe,
initW ithSecretCode:. secretCo

. , ^
i n it .

? WallSafe - ?
in it. - :
WallSafe *ws - [[W allSafe a llo c ] i n i t ] ;

inrt

249

,
,
, :
| (id)init
{

@throw [NSException exceptionWithName:@"WallSafeInitialization


reason:@"Use initWithSecretCode:, not init"
u s e rI n fo :n il];

A p p l i a n c e , : p r o d u c tN a m e v o l t a g e . ,

Appliance.h

{
>

N S S trin g * p ro d u ctN am e;
i n t v o lta g e ;

. :

( v o id )s e tP ro d u c tN a m e :( N S S trin g * ) s ;
(N S S trin g *)pro d u ctN am e;
( v o id )s e tV o lta g e :(in t)x ;
( in t) v o lta g e ;

@ p ro p e rty :

0 p r o p e rty (co p y ) N S S trin g *productN am e;


g p r o p e rty i n t v o lta g e ;
A p p l i a n c e . m .

- (v o id )s e tP ro d u c tN a m e :(N S S trin g * ) s

{
>

productName [s co p y ];

- (N S String *)productName

{
r e tu r n
>

productName;

C
j
N
s

2S l
- (v o id )s e tV o lta g e :( in t )x

{
'}

v o ltag e x;

|* - ( in t) v o lta g e

P{

>

retu rn v o lta g e ;

@synthesize:
gsynthesize productNam e, v o lta g e ;
O b jective-C:
iO S 6 4 - M a c O S X
. @ p ro p e rty /@ s y n th e s iz e ,
.
A p p l i a n c e .h :

{
}

/ / NSString *productNam e;
/ / in t v o lta g e ;

.
.

3 2 - Mac OS X.
.


,
.

/ (readw rite)
( read o n ly ). readurite,
, s e t - , g e t -. ,
s e t -, readonly:
ft>roperty (readonly) i n t v o lta g e ;

252

30

unsafe_unretained, strong,
weak . , s e t - .
unsafe_unretained ;
.
:

I
j
I

jj|fH
jil|
00

@property (unsafe_unretained) in t averageScore;


/ / "@property in t averageScore"
@synthesize averageScore;

II

II

s e t - .

- (void)setAverageScore:(int)d
{

averageScore = d;
>

A ppliance v o lta g e . safe_u n retain ed , -


.
stron g, 20,
.
( ). , ,

II

! [x

|ffl
HithZ
1

strong.

weak . set, .
n i l. ( :
unsafe_unretained, ,
, *>>.
.)
.
,
...

fel

* 1111'1
;

%e

Rlpw6^ caov*ST~~^
0property (copy) NSString *lastName;
gsynthesize lastName;

s e t - :
. (void)setLastName:(NSString *)d
{

lastName = [d copy];

>

,
. , NSString NSMuta b le S tr in g . , setLastName:
:
//

NSMutableString *x = [[NSMutableString alloc] initW ithString:@ "O noH];


// setLastName:
[myObj setLastName:x];
// ' * th is lastName
[x appendString:@" Lennon"];
?
.
copyWithZone: n il. , NSString copy
WithZone : :

- (id)copyWithZone:(NSZone *)z
{

retu rn s e l f ;
}

, . ( , NSZone
,
C o c o a , . ,
copyWithZone:
.)
, ,
^ . , NSMutableString
**W NSString. ,
, mutableCopy.
mutableCopy .
, s e t - ,
^ * , mutableCopy
^AHoro . , OwnedAppliance
*tOwnerNames::

Z54

30

- (void)setOwnerNames:(NSSet *)newNames
{
ownerNames = [newNames mutableCopy];
>


Objective-C copyWithZone:,
Objective-C ,
, mutableCopy NSObject
:
- (id)copy
{
return [ s e lf copyWithZone:NULL];
>
- (id)mutableCopy
{
return [ s e lf mutableCopyWithZone:NULL];
>

,
Appliance *b = [[Appliance a llo c ] i n i t ] ;
Appliance *c [b copy];

:
-[Appliance copyWithZone:]: unrecognized selector sent to instance
0x100110130

^ffiT

, a t o m i c / n o n a t o m i c
^^^^^|^|^|^^^^^^
. ^^|^f|
: nonatomic s e t -
^
U I K it , , 11- .
nonatomic. n ^ p
( .
^
, , . :
^-o
, ooeci
^*
s e t - * . : , ^ ^
. , s e t - 08

255

. *. , s e t -
. , .)

Appliance.h

nonatomic:

0property (copy, nonatomic) NSString


giproperty (nonatomic) in t voltage;

*productName;

, ato m ic
, .

-
- .

NSObject,

main.m

[a setProductN am e:@ "W ashing M a c h in e "];


-:

[a setV alue:@ "W ashing M achine" forKey:@ "productNam e"];

setV alu e: forK ey:, NSObject,


| s e t- setProductN am e:.
setProductName:, .
- .

[ m

a in .m

in t main ( i n t a r g c , c o n s t c h a r * a r g v [ ] )
0 a u to re le a se {

fJiI"

A ppliance * * [[A p p lia n c e a l l o c J i n i t ] ;


NSLog(0"a i s % @ "j ) ;
[a setV alu e:0 "W ashing M achine f o r K e y : " p r o d u c t N a m e " ] ;
[a se tV o lta g e :2 4 0 ];
NSLog(#"a l s W ' , a ) ;

NSLog(0"the p ro d u c t name i s 0", [a


v*lueForKey:f"productNam e"])j

256

30

v a lu e F o rK e y : , NSObject, ^
productName. productName ,
.
,
,
main.m:
NSLog(@"the product name i s %@",
[a valueForKey:@"productNammmme ]);


:
*** Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<Appliance 0xl00108dd0> valueForUndefinedKey:]:
t h is c la s s is not key value coding-compliant fo r the key
productNammmme.'

, .
- ? ,
, j
s e t V a lu e :f o r K e y :. , j
, v a lu e F o rK e y : . ,
Data SQLite
. , ,
-.
, -
, @ property productName eAppliance.h:
#import <Foundation/Foundation. h>
@interface Appliance : NSObject {
NSString *productName;
in t voltage;
>
// 0property (copy) NSString *productName;
gproperty (nonatomic) in t voltage;
//
- (id)initWithProductName:(NSString *)pn;

@end

se tP r o d u c tN a m e 11 |
ductName Appliance.m\

*57

0iwplementation Appliance
^synthesize voltage;

- (id)initWithProductName:(NSString *)pn
^

self * [super i n i t ] j
i f (self) {
productName = [pn copy];
[s e lf setV o ltag e: 120 ];
>
return s e lf;

}
(id )in it
return [ s e lf initWithProductName:@"Unknown"];

(NSString *)description
return [NSString stringWithFormat:@"<%@: %d
productName, voltag e];

volts>",

0end
.
productN am e,
. - ,
, . -
, .

-
- ,
8 : - ( , int float (* voltage i n t ) . voltage
- ? NSNumber.
main.m , voltage:
[a setVoltage:240];

:
1* &etValue.-[NSNumb numberWithInt:240] f o r K e y : 0 " v o lt a g e " ] ;

258

30

Appliance.m :
- (void)setV oltage:(int)x
{

NSLog(@"setting voltage to %d", x);


voltage * x;

.
valueForKey:@"voltage"
NSNumber, voltage.

*
. , A p p le NSString.
, N S S t r i n g .
Foundation VowelCounter. , Objective-C
(Objective-C c a t e g o r y ) . VowelCounting
N S S t r i n g .

NSString+ VowelCounting.h

NSString:
#import < F o u n d a tio n /F o u n d a tio n .h >

Ginterface N S S tring (VowelCounting)


- (int)vow elC ount;

0end
NSString+ VowelCount.tn.
#import "NSString+VowelCounting.h"

#implementation N S S trin g (V ow elCounting)


* (in t )vowelCount
NSCharacterSet * c h a rS e t *
,* ecmString:@"aeiouyAEIOUY"]j
[NSCharacterSet characterSetWithCharactersln
NSUlnteger co u n t [ s * H le n g th ]>
in t sum 0;
fo r ( i n t i ; i < c o u n t; i ++) t

260

31

unichar [ s e lf ch ara cterA tIn d ex :i];


i f ([charSet characterIsMember:c]) {
sum++;
>
>
return sum;
>
@end

main.m:
#import <Foundation/Foundation.h>
#import "NSString+VowelCounting.h"
in t main ( in t argc, const char * argv[])
{
@autorelease {
NSString *string = @"Hello, World!";
NSLog(@"%@ has %d vowels", s trin g , [strin g vowelCount])j
>
return 0 ;
>

. , ?
.
Vr0
, ,
, ,
.

24 :
.
- .
, .
,
, .
, Callbacks 24
,
zoneChange:.
, , zoneChange:
, . Callbacks

, , ,
.
Mac OS X 10.6 iOS 4
(blocks). Objective-C ( ), .
, .
Objective-C, .
8 Apple .
, .
, ,
bI ,
-. ,
- , ,

,
.


:
{

NSLog(0"I'm a log statement within a b lo ck !");

>
, .
. , ,
, :
^(double dividend, double d iv is o r) {
double quotient = dividend / d iv is o r ;
return quotient;

>
double.
, .
? . (, ,
5).
, .


, , .

.
Foundation Vowel
M o v e m e n t. 0
.
: ,
, , main.m

@autoreleasepool:
int main (in t argc, const char * argv[])

^ rm w m * w m

u/fUMnuH

0a u to relea sep o o l {

/ / , ,
/ /
NSArray * o ld S tr in g s [NSArray arrayHithObjects:
" S a u e r k r a u t" j Q"Raygun", "Big Nerd Ranch\
& " M is s is s ip p i" , n i l ] ;
NSLog(0"old s t r i n g s : %Q", o ld S tr in g s );
NSMutableArray * n ew S trin g s = [NSMutableArray array];
// ,
NSArray *vowels = [NSArray arrayH ithO bjects:
0 "a"j 0 " e " , g " i " j Q"o", 0 "u", n ilJ ;

}
return 0;

)
; .
.
.


- ' ^
^
"
^
^

^
.


,
main.m,
int main (in t argc, co n st ch ar * a rg v [])

0autoreleasepool {
* ,
/ / ,
/ /
,,n*hnM ects:
NSArray *oldS trings = [NSArray a^ra^,.Bi Ner(j Ranch",
0"S auerkraut", 0"Raygun , 0 Big Nera
@"Mississippi"* n i l ] ;
NSLog(0"old s trin g s : %@", o ld ? ^ ^ f a b le A r r a y array];
NSMutableArray *newStrings = [NSMutabieA
/ / ,
NSArray *vowels = [NSArray arrayW ithObjects.
@"a", @"e", @"i ", @"o", Q"u"* n l l J'

&

//
void (^ devow elizer)(id, NSUlnteger, BOOL *);

}
return 0;
>
, .

void (^ d ev o w elizer)(id , NSUInteger, B00L*)

. 32.1.
, -
, in t i. ,
. . devow elizer ,
, BOOL
.


.

main.m :
in t main (in t argc, const char * argv[])

@ a u t o r e le a s e p o o l {
// , >
//
NSArray *oldStrings [NSArray arrayWithObjects:
@"Sauerkraut", @"Raygun", @"Big Nerd Ranch",
@"Mississippi", n il] ;
NSLog(0"old strings: %@", oldStrings);
NSMutableArray *newStrings * [NSMutableArray array];

^^^
// ,

NSArray *vowels = [NSArray arrayWithObiects@"a", @"e", @"i", @o", @"u", n il];


//

void ( ^ d e v o w e liz e r )( id , NSUlnteger, BOOL *);


//

devowelizer = A(id s trin g , NSUlnteger i , BOOL *stop) {


NSMutableString *newString = [NSMutableString
stringWithString:string] j
//
//

fo r (NSString *s in vowels) {
NSRange fullRange = NSMakeRange(0, [newString length]);
[ newString replaceOccurrencesOfString:s
withString:0""
options:NSCaseInsensitiveSearch
range:fullRange];

[newStrings addObject:newString];

}; //

}
return 0;

}
, .
.
, ( )
d e v o w e liz e r. :
;, .
d e v o w e liz e r ,
:
void (^ d ev o w elizer)(id , N SUlnteger, BOOL *) = ^(id string, NSUlnteger
i , BOOL *stop) {
NSMutableString *new String * [NSMutableString
strin g W ith S trin g :strin g ];
//
//

f or (NSString *s in vowels) {
NSRange fullR ange = NSMakeRange(0, [newString length]);
[newString replaceO ccurrencesO fString:s
w ithString:@ ""
options:NSCaseInsensitiveSearch

ran ge: fu llR a n g e ] ;

}
[new Strings addO bject:new String];

};
,
devow elizer,
devow elizer.


d e v o w e lize r , .
NSArray enumerateObjectsUsingBlock:.EMH ,
.
main.m , enumerateObjectsU singBlock: devowelizer,
.
in t main ( in t arg c, const char * arg v[])

@ autoreleasepool {
// , ,
//
NSArray * old S trin g s = [NSArray arrayWithObjects:
@"Sauerkraut", @"Raygun", @"Big Nerd Ranch",
@ "M ississip p i", n i l ] ;
NSLog(@"old s tr in g s : %@", o ld S trin g s );
NSMutableArray *newStrings = [NSMutableArray array];
// ,
NSArray *vowels = [NSArray arrayWithObjects:
@"a", @"e , @4 " , @"o", @"u", n i l] j
//
v o id (^ d e v o w e liz e r)(id , NSUInteger, BOOL *)j
//
devow elizer = ^(id s t r in g , NSUInteger i ,

BOOL *stop) {

NSMutableString *newString = [NSMutableString


s tr in g W ith S t r in g :s t r in g ] ;
//
//

for

( N S S trin g *s in

vowels) {

NSRange fullR ange = NSMakeRange(9, [newString lengthl)[newString replaceOccurrencesOfString:s

withString:@""
options:NSCaseInsensltiveSearch

^ " \

r a n g e :f u l lR ange];

}
fnewStrings addObject:neuString];
}; //

/ /

[oldStrings enumerateObjectsUsingBlock:devowelizer];
NSLog(0"new s t r in g s : %0, new Strings)j

}
retu rn 0 ;

}
. .
.
2011-09-03 10:27:02.617 VowelMovement[787:707] old s tr in g s : (
Sauerkraut,

Raygun,
"Big Nerd Ranch",
Mississippi

)
2911-09-03 10:27:02.618 VowelMovement[787:707] new s tr in g s : (
S rk rt,
Rygn,
"Bg Nrd Rnch",
Msssspp

)
, e n u m e ra te O b je c ts U s in g B lo c k :
. , ,
, BOOL,
^. , d e v o w e liz e r,
.

.
. . id, ,
Nsuit 0 ) .
nteger .

268

32

BOOL, N0. ,
,
:
devow elizer ^(id s t r in g , NSUInteger i ,

BOOL *stop){

NSRange yRange * [ s t r in g rangeO fString:0"y"


o p tio n s : NSCaseInsensitiveSearch];

/ / " "?
if

(yR ange.location != NSNotFound) {


*stop - YES; //
retu rn ;
//

}
NSMutableString *newString = [NSMutableString
strin g W ith S trin g :strin g ];
//
//
fo r (NSString *s in vowels) {
NSRange fullR ange = NSMakeRange(0, [newString length]);
[newString replaceO ccurrencesO fString:s
w ithStrin g:@ ""
o p tio n s :NSCaseInsensitiveSearch
range:fu llR a n g e ];

>
[newStrings addObject:newString];
}; //

, #
. ,
YES ( ), #
.
.
,
. S rk rt.

, .
,
. o6pa
24, :
[ [N S N o tifica tio n C e n te r de fa u ltC en ter]
addObserver: logger

selector:@ selector(zoneC hange:)


name: NSSystemTimeZoneDidChangeNotification
o b je c t:n il];

( @selector()),
- :
I (yoid)zoneChange:(NSNotification *)note
NSLog(@"The system tim e zone has changed!'');

}
NSNotificationCenter
addObserverForName: o b je c t: queue: usingBlock: .
NSNotificationCenter
,
- .
, NSNotificationCenter, .
( Callbacks .)

typedef
,
ty p e d e f , 10. ,
ty p e d e f ,
- . main.m :
#import <Foundation/Foundation.h>
typedef void (^A rrayEnum erationBlock)(id, NSUlnteger, BOOL *);
int main (in t argc, const char * arg v [])
ty p e d e f .
& , ,
*^> . typ edefyn pou iaeT
I ^ . devow elizer:
void (^devowelizer)(id, NSUlnteger, BOOL *);

^ :
ArrayEnumtrfttionBlock devowelizer;

270

32
l

, .
, .
;
.


, ,
.
double (^divBlock)(double,double) = ^(double k, double j) {
return k/j;

>
divBlock,
double double .
,
.
:
double quotient = divBlock(42.0, 12.5);


, , .
,
, .
, -
, .
.
,
ArrayEnumerationBlock iVarDevowelizer = [devowelizer copy];

, *
.
, (, enum erateO bjects
ingBlock: KflaccaNSArray addObserverForName:object:queue:using
ck: N S N o tifica tio n C e n te r), &10
.
,

l l C *

271

, , ,
. , .
, .

.
, ?

( ,
), .
,
.

.
, . , ,
,
, . ( ,
? -
!)
VowelMovement. devowelizer
, : newStrings (
) string ( ,
). devowelizer ,
, .
?

, . : .
C__weak), .
, ?

, ,
, . ,
. (
, ,
.)
.
block. ,
counter;
__block int counter 0;
void (AcounterBlock)() A{ counter++; >;
4 (

&

272

32

counterBlock(); // counter 1
counterBlock(); // counter 2

_block , , counter


, ,
. , ,
M a c iO S . 1 .
, A L A s s e tL ib r a r y G a m e K it
.
A p p le , .


, .
( , numberW i t h I n t : NSNumber), i n t :
// 1:
in t i ;
i = 5;
NSNumber *num = [NSNumber numberWithInt:i];
// 2:
NSNumber *num = [NSNumber numberWithInt:5];

,
. , <^
. ^
;
.

273

,
enum erateO bjectsU singBlock: . , ,
.

NSNotificationCenter
24 addO bserver: s e l e c t o r : name:o b je c t : NSNotifica
tionCenter
zoneChange:. ,
addO bserverForN am e:object:queue:usingB lock:.
.
,
,
. , zoneChange : , ,
, .
(N S N o tific a tio n *)
, zoneChange:.
queue: nil;
, .



O b je c tiv e - C
,
^^^ ^. , ,
^^ .
Ynm 6^ ,
.


,
. ; 1
, 0 .
,
. 8-
, 2(.
33.1).
128

64

32

16

32 + 16 + 8 + 4

=60

. 33.1. , 60

||^ ^ S
, 10 .
2. ^
(16 24)
.
.
^ ^
a, b, , d, e f. ,
: 0, 1, 2, 3,4, 5, 6, 7, 8, 9, a, b, , d, e, f, 10, 11,...

, ,
0x. I la . 33.2 , . 33.1 uiec
.

V\r\V\
0 x 8 0 0 x 4 0 0 x 2 0 0 x 10 0 x 8

*77

0 x 4 0x2 0x1

0
0x20+ 0x10 + 0x8 + 0x4

. 33.2. ,

= 0x3c

0x3c


( , ) . . ,
- : ,
.

? T e rm in a l hexdump :
$ hexdump m
0000000
0000010 2 e
0000020 7 3
0000030 6 b
0000040 2 2
0000041

y f ile .t x t
3 f78 6d
3022 3 f
3d 2 2 6 8
2e6f 7 2

74
67

20
0a
74
2f

76

70
6e

65
62

73

72
6f
2f
2f

73
6f
2f
64

69
6b
64
6f

6f 6 e

3d
20 7 8 6d
6f 6 3 6 2
6 3 6 2 6f

22
6c
6f
6f

31
6e
6f
6b

( )
, .
.


;
. 1 ,
1.
| .
: (
Foundation!) bitw ize.
main.c.
#include <stdio.h>
|nt main (int argc, const char * a r g v [ ] )

unsigned c h a r ;

278

33

unsigned char b = 0xa9;


unsigned char = a | b;

I
1

printf("Hex: %x | %x = %x\n", , b, );
p rintf< "Decimal: %d | %d = %d\n", a, b, ) ;
return 0;

jJ

1 | 1

0x3c

= Oxbd

. 33.3.


:
Hex: | a9 = bd
Decimal: 60 | 169 = 189

? Objective-C
.
, ,
/ . (
) , . ,
,
. ,
, .
. iOS NSDataDete cto r. NSDataDetector
, URL-.

.
fyauRe NSDataDetector.h : NSTex

LinK>
CheckingTygepate, NSTextCheckingTypeAddress, NSTextCheckingType
NSTextCheckingTypePhoneNumber N S T e x tC h e ck in g T y p e T ra n sitIn fo rm a tio

NSDataDetector ,
. , Z ?
:
NSError *e;

NSDataDetector *d = [NSDataDetector dataDetectorWithTypes:


e r r o r ^ & e ] ^ k in 8 T y P e P h neNUmber ^NSTextcheckingTypeOate


C o c o a iO S;
.



. 1 ,
1.

= 0x3c

= 0xa9

= 0x28

33.4.

&. main.c
:
#include <stdio.h>
int main (in t argc, const char * a rg v[])

{
unsigned char - 0x3c;
unsigned char b = 0xa9;
unsigned char = a | b;
printf("Hex: %x | %x %x\n", a, b, );
printf("D ecim al: %d | %d %d\n", a, J );

280

unsigned char d = & b;


printf("Hex: Xx & %x = %x\n", a, b, d);
printf("Decim al: %d & %d = %d\n", a, b, d);
re tu rn 0;

>

:
Hex: & a9 = 28
Decim al: 60 & 169 = 40

Objective-C
( ). ,
NSDataDetector ,
:
if

unsi

([cu rre n tD e te cto r checkingTypes] & NSTextCheckingTypePhoneNumber) {


NSLog(@"This one i s lo o k in g f o r phone numbers");

>

JQjrir

\ Z Z Z Z Z Z Z Z Z ^ _ _ _ _ _ _ _ _ _ _ _ _ ;_ _ _ ^ _ _ _ _ _ ^ ^ ^ ^ ^ ^ _

checkingTypes ,
,
N S D ataD etecto r.
NSTextCheckingType, . , NSTextCheckingTypePhoneNumber, NSDataDetector,
.
, , NSDataDetector .

prifi

retu

^PorpajM
| *tex:jc
x:

I ^^
| |
___

S*


5r

onepa^
. Objective-C, .

iH i

!.

f^ V ^
\%

.
|<* ' II ^
1 , - j %.Q4

sS^

=0x3c

=0xa9

=0x95

281

. 33.5.

^, main.c
:
unsigned char e a A b;
printf("Hex: %x %x = %x\n", a, b, e);
printf(''Decimal: %d %d = %d\n", a, b, e);
return 0;

}
:
Hex: a9 = 95
Decimal: 60 ^ 169 = 149


.
: 2^3 2 3.
pow():
double = pow(2.0, 3.0); // 2

: ,
.
~ .
nuan.c.

282

33

unsigned char f = ~b;


printf("H ex: The complement of %x is %x\n"j b, f ) j
printf("D ecim al: The complement of %d is %d\n", b, f) ;
return 0 ;

= 0xa9

= 0x56

. 33.6.
:
Hex: The complement of a9 is 56
Decimal: The complement of 169 is 86



. , , ,
.
0

/V V 2 s

_ 2

_____ l>r

d/

jf

Jf

/
0

= 0x3c
0
7------

/
0

0xf0

. 33.7.

<<. matn
:
unsigned char g << 2 ;
printf("Hex: shifted le f t tw o places is %x\n", a, g)>

printf ("Decima1:

%d s h ifte d le f t two places is

jg

%d\n"
^ ^^ E)>

return 0 ;

}
:
Hex: sh ifte d l e f t two places is f0
Decimal: 60 s h ifte d l e f t two places is 240


.
:
unsigned char h = >> 1 ;
printf("H ex: %x s h ifte d rig h t one
printf("D ecim al: %d s h ifte d right

place is %x\n", a, h);


one place is %d\n", a, h);

return 0 ;

>
:
Hex: 3c shifted rig h t one places is le
Decimal: 60 sh ifte d rig h t two places is 30

1 H~0~ =0x3c

0 / =0x1e

. 33.8.

enum

,
.

284

33


( . ) .


^ ^ k


. Ham> ^
U ID a ta D e te c to r :
^enum {
U ID ataD etectorT ypePhoneN um ber
U ID ataD etecto rT y p e L in k
U ID a ta D e te c to rT y p e A d d re ss
U ID a ta D e te c to rT y p e C a le n d a rE v e n t
U ID ataD etecto rT y p eN one
U ID a ta D e te c to rT y p e A ll

};

=
=
*
=
=

1 <<
0,
1
1,
1
2
1 <<
3,
0,
N S U IntegerM ax

unsigned char,

8--

. .

NSTextCheckingTypePhoneNumber
u in t64_ t 6 4 - .

, 6 4 -

. ( :
; .) .

O b j e c t iv e - C ,

NSString

. , .

?
O bjective-C. , ,
PostgreSQL.
,

NSString.

char

. .
, . , ,
A S C I I ( A m e r ic a n S ta n d a rd Cod e for Information
Interchange). A S C I I .
, 0x 4 b .

y o strin g .

A S C I I .

#include <stdio.h>
int nain (int argc, const char * argv[])

char x 0x21; / / 111


while (x < Ox7e) { / / '~ '
printf("%x is %c\n"j x, x)j

>
)

X+*J

return 0;

main.c:

286

34

: 256
94 . ? t N
, ASCII
. ,
( ). , 7 ^
ASCII . 0-31 ASCll ^**
: 32 . 127 &^
. . 128-255? ASCll iw^
7 6irroB. 128 ASCII- .
ASCII , &*
. :
int main (int argc, const char * argv[])
{
char x = ' ! j / / ' ! '
while (x <= '~') { / / '~'
printf("%x is %c\n''j x, x)j
x++;
>
return 0:
.
, \. \n
.
:
34.1.

\n

\t

40

- (0x00)

cnar*

287

char*
, *
. 0 x 0 0 * ' '* '

0x4c

0x6f

'L '

'0 '

0x00

0x76 0x65
'V*

'e ' '\0 *

. 34.1. Love
, ,
. ,

s tr le n ( )

strlen()

# in c lu d e < s t d i o . h >
/ / For p r in tf
#include <stdlib.h> // For m alloc/free
#include <string.h> // For s t r le n
i n t main ( i n t a r g c , c o n s t c h a r * a r g v [ ] )

char x * ' ! ' ; / /

T he c h a r a c t e r *!*

w h ile (x <= ' ~ ' ) { / / T he c h a r a c t e r


p r i n t f ( " % x i s % c \n " , x , x ) ;
x++;

'~ '

>

// 5
char * sta rt = m a llo c(5 );
// 'L '
*start ' L ' ;
// 'o '

* (sta rt + 1) = 'o ';


/ / ' v '
(*tart + 2) ' v ' j
/ / ' e '
(tart 3) *';
//

&

* ( s t a r t + 4) = '\ 0 ';
//
p rin tf("% s has %zu c h a ra c te rs \ n " j

s ta rt,

s t r le n ( s t a r t ) ) ;

//
p r in t f ( " T h e t h ir d l e t t e r i s %c\n", * ( s t a r t + 2 ) );
//
fre e (sta rt);
s t a r t = NULL;

r e tu rn 0;

.
.
s ta r t char *. char .
s ta r t+ l , 1
s ta r t; sta r t+ 2 2 . .
start
L

start+1 start+2 start+3 start+4


V
e
\0

. 34.2.


, :
s t a r t [ 2 ] *^ : + 2). :
char * s ta r t = m alloc(5);
s ta r t[0 ] ' L ' ;
s t a r t [ l ] = 'o* i
start[2] ' v ' ;
s ta r t[3 ] * ' e ' ;

start[4] '\0 ';


p rin tf("% s has %zu characters\n", s ta r t, s trle n (s ta r t)) ;
p rin tf("T h e th ir d le t t e r is %c\n", s t a r t [ 2 ] ) ;
fr e e ( s ta r t) ;

start NULL;

>

return 0;

------------ ">^HPiibi

289

,
, :
i n t m ain ( i n t a r g c , c o n s t c h a r * a r g v [ ] )
/ / ,
/ / f l o a t
f l o a t * f a v o r i t e s = ttia llo c (3 * s i z e o f ( f l o a t ) ) ;
/ /

fa v o rites[0 ] = 3.14158;
f a v o r ite s [l] = 2.71828;
fa v o rites[2 ] = 1.41421;

%.

*k
^
.

/ /
f o r ( i n t i = 0 ; i < 3 ; i+ + ) {
p r i n t f ( " % . 4 f i s f a v o r i t e % d \n " , f a v o r i t e s [ i ] , i ) ;

>

/ /
fre e (fa v o rite s );
f a v o r i t e s = NULL;

re tu rn 0 ;

, fa
vorites f l o a t *. flo a t 4 . ,
fa v o r ite s + l 4 OTHomeHfflOKfavorites.


,
malloc .
( -),
. ,
:
int main (in t argc, const char * argv[])

char x ' ! ' ; / / ' I '


while (x < ' ~ ' ) { / / '~ '
printf("%x is %c\n", x, x);

&

char *start = "Love";


printf("%s has %zu characters\n", sta r t, strlen (sta rt));
printf("The third le tte r i s %c\n", sta r t[2 ]);
return 0;

.

malloc . ,
, .
:
.
:
char * sta rt = "Love";

start[2] = 'z';
printf("Xs has %zu characters\n", s ta r t, str le n (sta r t));

o6
EXC_BAD_ACCESS. ,
.

, const ,
, . :
const char *start = "Love";
sta r t[2 ] = 'z ';
printf("%s has %zu characters\n", s ta r t, str le n (sta r t));


.
(s ta r t[2 ] = ' z ' ;), .
. :
const char *start = "A backslash a fter two newlines and
a ta b :\n \n \t\\" ;
printf("%s has %zu characters\n", sta r t, strlen (sta rt));
printf("The third le tte r is \'% c\'\n", sta r t[2 ]);
return 0;

)
.

NSString
Objective-C,
NSString . NSString
:
char *greeting "Hello!";
NSString *x = [NSString stringWithCString:greeting
encoding:NSUTF8StringEncoding];

NSString.
, NSString
, .
, :
NSString *greeting = "Hello!";
const char *x =NULL;
if ([greeting canBeConvertedToEncoding:NSUTF8StringEncoding]) {
x = [greeting cStringUsingEncoding:NSUTF8StringEncoding];

}
;
. ,
, autorelease;
, ,
malloc().

spaceCount() (ASCII
0x20) . :
#include <stdio.h>
int main (int argc, const char * argv[])

{
const char * sentence * "He was n o t in th e cab at the time.";
printf("\"% s\" has %
d s p a c e s \ n " , se n te n c e , spaceCount(sentence)),

>

return 0;

. ,
,
.
, .
,
,
.
g ra d eIn T h eS h ad e.

main.c:
#include <stdio.h>
#include <stdlib.h> // m alloc(), free()
flo a t averageFloats(float *data, in t dataCount)

flo a t sum = 0 . 0 ;
fo r (in t i = 0; i < dataCount; i++) {
sum = sum + d ata[i];

>

return sum / dataCount;

}
in t main ( in t argc, const char * argv[])

// flo a t
f lo a t *gradeBook malloc(3 * s iz e o f( flo a t ) ) ;
gradeBook[0] 60.2;
gradeBook[i] 94.5;
gradeBook[2] 81.1;
//


flo a t average = averageFloats(gradeBook, 3).

*93

//
free(gradeBook);
gradeBook = NULL;
printf("Average = %.2f\n", average);
return 0 ;

}
.

. 35.1. float

m alloc () ,
, .
( ),
? , .
main.c\
import <stdio.h>
float averageFloats(float *data, in t dataCount)

{
float sum .;
for (int i s 0 ; i < dataCount; i++) {
sum s sum + data[i];

)
return sum / dataCount;

|"t main (int argc, const char * argv[])


//

294

35

flo a t gradeBook[3];
gradeBook[0] = 60.2;
gradeBook[l] = 94.5;
gradeBook[2] = 81.1;
/ /
flo a t average = averageFloats(gradeBook, 3);
/ / !
/ /
/ /

printf("Average = %.2f\n", average);


return 0;

}
.
.
.
gradeBook:
in t main (in t argc, const char *argv[])

{
f lo a t gradeBook[] = {60.2, 9 4 .5 , 81.1};
flo a t average = averageFloats(gradeBook, 3);
printf(*'Average = %.2f, average);
return 0;

}
.
: , gradeBook 3, ;
.
, *. ,
a v e r a g e F l o a ts ( ) :
flo a t averageFloats(float d ata[], in t dataCount)

flo a t sum = 0.0;


for (in t i - 0; i < dataCount; i++) {
sum * sum + d a ta [i];

>

return sum / dataCount;

>
.

m a i n ( ) ,

:
i n t m a in ( i n t a r g c , c o n s t c h a r * a r g v [ ] )

{
, argv - ; argc
. ?
.
, ,
T e r t n in a l- ,
(shell). : csh, sh, zsh ksh,
Mac bash. bash
,
. argv main().

, Cocoa iOS argv argc.



.
Xcode
A f f i r m a t i o n . A f f i r m a t i o n .'
n, n .
%Affirmation Mikey
** is cool.
1* is cool.
N i ^ A ti

J _

____*

296

36

#include <stdio.h>
in t main (in t argc, const char * argv[])

fo r (in t i = 0; i < argcj i++) {


p rin tf("a rg %d = %s\n", i , argv[i])j

>
return 0;

>
bash, :
$ Affirmation Aaron 4

iMSi& ct

Q Affirmtftat - main.m
Flnlshtd rvnning Armition

.tfMJLJI
Affirmatiofl

; A fftrm M ion

B__11 u ^ n , *

Scftinw

..
Affirm | _ *

B u ttd

p^WWW^^W^^W^WW\^^WJJ^

l *

.,_, Suppo

Base bpwihM is On I

>frw4wd|
P ro d u c t*

j . lAji, T t l

| i * m Oetwg
fro tte Afllrm*tion
^* R**e*t*

A<firm*Mon
ffv.iMiv<Mtttep* *,,0,) vritt **<.

,^1|^^^^^^8^$^8|88$^
.........
Aaron

1 1 IiBggsB;'4i^:^:.w.^
*
:' S.<
$ ^^^^ ^^ 1 ^ <^8^'

**An*brw
Dtb*m
* ArcMhM

I--W
MW^**
W~v-.'}.~...l.-..-..-. J'.. .t>l-.-...teV.. ... . .' .|..-.v-- .-...,..
Environment VWMMii
!Nimt

^^^^^^^^^^^^^^^^^^*^1*

ime>

I0l allo

!Vatuc

^Atemt4^
!,,

'. ":.;:.. ;,'-,:

1
!

-,
i M
.,,.,:..,;
^^^^^.^^

I
vj H
C~ Qupllc*t> 5ehm

) (

M > ro ia* S ch < n w > ..,)

01* * * ,

. 36.1.

n0lB#-

n$w
. Product Edit Schef^

297

Run AfFirmat\on
A rg u m e n ts . Arguments pL*O n
U u n c n + : .
OK, .
argv .
argv[0]:
arg

0 = /Users/aaron/Library/Developer/Xcode/DerivedData/
Affirmation-enkfqsgavfsproeggoxwbrmcowvn/Build/Products/Debug/
Affirm ation
arg i = Aaron
arg 2 = 4

argv[0] .

3yV

______ ^ ---"Build/Products/Debug/Affirmation"
____
0
**"Aaron"

argc = 3

^^~^

. 36.2. argv argc Affirmation

, ,
. mmnm.
#include <stdio.h>
#include <stdlib.h> // a to i()
int main (int argc, const char * argv[])

{
if (argc != 3) {
fprintf(stderr, "Usage: A ffirm atio n <name> <number>\n");
return 1;

>
int count * atoi(argv[ 2 ]);
for (int j * 0 ; j < count; j++) {
printf("Xs is cool.\n", a rg v [l]);

return 0 ;

switch

,
. if-else
:
in t yeastType = . . . ;
i f (yeastType == 1) {
makeBread();
} else i f (yeastType == 2) {
makeBeer();
} else i f (yeastType == 3) {
makeWine();
} else {
makeFuel();

>
switch.
:
in t yeastType = . . . ;
switch (yeastType) {
case 1:
makeBread();
break;
case 2:
makeBeer();
break;
case 3:
makeWine();
break;
default:
makeFuel();
break;

>

swircn

break.
c a s e
c a s e . , switch
:
in t yeastType = 2;
switch (yeastType) {
case 1:
makeBread();
case 2:
m akeB eer();
c a se 3:

makeWine();
d e fa u lt:
makeFuel();
}

m akeBeer(), makeWine() makeFuel().


,
:
in t yeastType = . . . ;
switch (yeastType) {
case 1:
case 4;
makeBread();
break;
case 2:
case 5:
makeBeer();
break;
case 3:
makeWine();
break;
default:
makeFuel();
break;
>
, break case -
,
.
sw itch :
case .
switch Objective*C,
.

,
iO S M a c O S X .
. ,
, .
, ,
. .
, Apple
O b j e c t iv e - C , .
, :
O b je c tiv e -C , . .
iO S ,
iO S P r o g r a m m in g : T h e B ig N e r d R a n c h G u id e . .
iO S , .
M ac OS X,
P r o g r a m m in g fo r M a c O S X
, .
,
.
iO S .
.
.


T w itter, B ig N erd R a n ch .^ ar
H ille g a s s

301

Big Nerd Ranch.

,
-
.
www.bignerdranch.com.

,
: , . ,
.


Objective-C. iOS MacOS
E.



i\

.
.

. A(tyt*<it'KrtJi
R

Ptx)uoH

. ltNi20ti, *6^ 1tow|>i4H|)CKOt> \ 7 ' \ ; A<W


jiMt)tM ' OK &, l4>M!
05 .4005 ***
11(111 iii>4ivrii 20.06.12. 70x100/10 Mvi. > .i> 24,510, 1\(| 1500 .W*KtM,5

*>tt rnno \''|*


IHt)tMM, llt ki>H, , l'otHMH, !14i


o=HKT-neTeF*Byprcw=CT

-SRLD.ru

8 (812)336-3739

OBJECTIVE-C. iOS MacOS


iOS ? ,
Objective-C, !
IT- Big Nerd Ranch,

Objective-C 1-.
Xcode 4.2, IOS 5 M ac OS X 10.7 Lion
, ,
Objective-C Apple.

: Objective-C. A p p le

ISBN: 978-5-459-01567-6

' : / :

^'
:
197198, -, / 127
.: (812) 703-73-74, postbook 9 plttr.oorn

9 " 7 8 5 4 5 9 01 5 6 7 6

=*
d

BiQ

n e rD

81093, -93, / 9130


.: (067) 768-41-46, 751-10-02, pltarOkharkov.ptof.com

www.plter.com -