Programming Ios 4 Fundamentals Of Iphone Ipad
And Ipod Touch Development 1st Edition Matt
Neuburg download
https://ebookbell.com/product/programming-ios-4-fundamentals-of-
iphone-ipad-and-ipod-touch-development-1st-edition-matt-
neuburg-2269492
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Programming Ios 4 Neuburg Matt
https://ebookbell.com/product/programming-ios-4-neuburg-matt-10509378
Programming Ios 4 Matt Neuburg
https://ebookbell.com/product/programming-ios-4-matt-neuburg-42957514
Programming Ios 4 Matt Neuburg
https://ebookbell.com/product/programming-ios-4-matt-neuburg-42918746
Advanced Ios 4 Programming Developing Mobile Applications For Apple
Iphone Ipad And Ipod Touch 1st Edition Maher Ali
https://ebookbell.com/product/advanced-ios-4-programming-developing-
mobile-applications-for-apple-iphone-ipad-and-ipod-touch-1st-edition-
maher-ali-2031638
Ios 4 Programming Cookbook Solutions Examples For Iphone Ipad And Ipod
Touch Apps 1st Edition Vandad Nahavandipoor
https://ebookbell.com/product/ios-4-programming-cookbook-solutions-
examples-for-iphone-ipad-and-ipod-touch-apps-1st-edition-vandad-
nahavandipoor-2372508
Ios 4 Programming Cookbook Vandad Nahavandipoor
https://ebookbell.com/product/ios-4-programming-cookbook-vandad-
nahavandipoor-31832786
Learn Ios 11 Programming With Swift 4 2nd Edition Craig Clayton
https://ebookbell.com/product/learn-ios-11-programming-with-
swift-4-2nd-edition-craig-clayton-38506028
Mastering Ios 11 Programming Build Professionalgrade Ios Applications
With Swift 4 And Xcode 9 Source Code Wals
https://ebookbell.com/product/mastering-ios-11-programming-build-
professionalgrade-ios-applications-with-swift-4-and-xcode-9-source-
code-wals-6856012
Mastering Ios 14 Programming Build Professionalgrade Ios 14
Applications With Swift 53 And Xcode 124 4th Edition Mario Eguiluz
Alebicto Chris Barker Donny Wals
https://ebookbell.com/product/mastering-ios-14-programming-build-
professionalgrade-ios-14-applications-with-swift-53-and-xcode-124-4th-
edition-mario-eguiluz-alebicto-chris-barker-donny-wals-23900324
Programming iOS 4
by Matt Neuburg
Copyright © 2011 Matt Neuburg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (http://my.safaribooksonline.com). For more information, contact our
corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com.
Editor: Brian Jepson
Production Editor: Teresa Elsey
Proofreader: Nancy Kotary
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
May 2011: First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Programming iOS 4, the image of a kingbird, and related trade dress are trademarks
of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
ISBN: 978-1-449-38843-0
[LSI]
1305160942
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Part I. Language
1. Just Enough C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Compilation, Statements, and Comments 4
Variable Declaration, Initialization, and Data Types 6
Structs 8
Pointers 10
Arrays 11
Operators 13
Flow Control and Conditions 15
Functions 19
Pointer Parameters and the Address Operator 22
Files 24
The Standard Library 27
More Preprocessor Directives 27
Data Type Qualifiers 28
2. Object-Based Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Objects 31
Messages and Methods 32
Classes and Instances 33
Class Methods 36
Instance Variables 37
The Object-Based Philosophy 39
3. Objective-C Objects and Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
An Instance Reference Is a Pointer 43
Instance References, Initialization, and nil 44
v
Instance References and Assignment 47
Instance References and Memory Management 48
Messages and Methods 49
Sending a Message 50
Declaring a Method 51
Nesting Method Calls 52
No Overloading 52
Parameter Lists 53
Unrecognized Selectors 53
Typecasting and the id Type 55
Messages as Data Type 58
C Functions and Struct Pointers 59
Blocks 61
4. Objective-C Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Class and Superclass 65
Interface and Implementation 66
Header File and Implementation File 68
Class Methods 71
The Secret Life of Classes 71
5. Objective-C Instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
How Instances Are Created 73
Ready-Made Instances 73
Instantiation from Scratch 74
Nib-Based Instantiation 77
Polymorphism 78
The Keyword self 79
The Keyword super 82
Instance Variables and Accessors 84
Key–Value Coding 86
Properties 87
How to Write an Initializer 89
Part II. IDE
6. Anatomy of an Xcode Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
New Project 96
The Project Window 97
The Navigator Pane 99
The Utilities Pane 103
The Editor 104
vi | Table of Contents
The Project File and Its Dependents 106
The Target 109
Build Phases 109
Build Settings 110
Configurations 111
Schemes and Destinations 112
From Project to App 115
Build Settings 117
Property List Settings 117
Nib Files 118
Other Resources 118
Code 120
Frameworks and SDKs 121
7. Nib Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
A Tour of the Nib-Editing Interface 125
The Dock 127
Canvas 128
Inspectors and Libraries 130
Nib Loading and File’s Owner 132
Default Instances in the Main Nib File 133
Making and Loading a Nib 134
Outlet Connections 135
More Ways to Create Outlets 139
More About Outlets 141
Action Connections 142
Additional Initialization of Nib-Based Instances 146
8. Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
The Documentation Window 150
Class Documentation Pages 152
Sample Code 155
Other Resources 156
Quick Help 156
Symbols 157
Header Files 157
Internet Resources 158
9. Life Cycle of a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Choosing a Device Architecture 159
Localization 162
Editing Your Code 163
Autocompletion 164
Table of Contents | vii
Snippets 165
Live Syntax Checking 166
Navigating Your Code 166
Debugging 169
Caveman Debugging 169
The Xcode Debugger 171
Static Analyzer 176
Clean 177
Running in the Simulator 177
Running on a Device 178
Device Management 181
Version Control 181
Instruments 184
Distribution 184
Ad Hoc Distribution 186
Final App Preparations 187
Icons in the App 188
Other Icons 189
Launch Images 189
Screenshots 190
Property List Settings 191
Submission to the App Store 192
Part III. Cocoa
10. Cocoa Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Subclassing 197
Categories 200
Splitting a Class 201
Private Method Declarations 201
Protocols 202
Optional Methods 206
Some Foundation Classes 208
Useful Structs and Constants 208
NSString and Friends 208
NSDate and Friends 210
NSNumber 211
NSValue 211
NSData 212
Equality and Comparison 212
NSIndexSet 213
NSArray and NSMutableArray 213
viii | Table of Contents
NSSet and Friends 215
NSDictionary and NSMutableDictionary 215
NSNull 217
Immutable and Mutable 217
Property Lists 218
The Secret Life of NSObject 218
11. Cocoa Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Reasons for Events 224
Subclassing 224
Notifications 226
Receiving a Built-In Notification 226
Unregistering 228
NSTimer 228
Delegation 229
Data Sources 232
Actions 233
The Responder Chain 237
Deferring Responsibility 238
Nil-Targeted Actions 238
Application Lifetime Events 239
Swamped by Events 243
12. Accessors and Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Accessors 249
Key–Value Coding 251
Memory Management 254
The Golden Rules of Memory Management 255
How Cocoa Objects Manage Memory 257
Memory Management of Instance Variables 260
Instance Variable Memory Management Policies 263
Autorelease 264
Nib Loading and Memory Management 266
Memory Management Comments on Earlier Examples 267
Memory Management of Pointer-to-Void Context Info 269
Memory Management of C Struct Pointers 270
Properties 271
13. Data Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Model–View–Controller 277
Instance Visibility 279
Visibility by Instantiation 280
Visibility by Relationship 281
Table of Contents | ix
Global Visibility 281
Notifications 282
Key–Value Observing 284
Part IV. Views
14. Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
The Window 293
Subview and Superview 295
Frame 298
Bounds and Center 299
Layout 302
Transform 305
Visibility and Opacity 308
15. Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
UIImage and UIImageView 311
UIImage and Graphics Contexts 313
CGImage 315
Drawing a UIView 318
Graphics Context State 320
Paths 321
Clipping 325
Gradients 326
Colors and Patterns 328
Graphics Context Transforms 330
Shadows 332
Points and Pixels 332
Content Mode 333
16. Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
View and Layer 336
Layers and Sublayers 337
Manipulating the Layer Hierarchy 339
Positioning a Sublayer 339
CAScrollLayer 340
Layout of Sublayers 341
Drawing in a Layer 341
Contents Image 341
Contents on Demand 342
Contents Resizing and Positioning 343
Layers that Draw Themselves 345
x | Table of Contents
Transforms 346
Depth 350
Transforms and Key–Value Coding 352
Shadows, Borders, and More 353
Layers and Key–Value Coding 354
17. Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Drawing, Animation, and Threading 358
UIImageView Animation 361
View Animation 362
Animation Blocks 362
Modifying an Animation Block 363
Transition Animations 366
Block-Based View Animation 368
Implicit Layer Animation 371
Animation Transactions 372
Media Timing Functions 373
Core Animation 374
CABasicAnimation and Its Inheritance 375
Using a CABasicAnimation 376
Keyframe Animation 379
Making a Property Animatable 380
Grouped Animations 381
Transitions 385
The Animations List 386
Actions 389
What an Action Is 389
The Action Search 390
Hooking Into the Action Search 391
Nonproperty Actions 394
18. Touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
Touch Events and Views 398
Receiving Touches 400
Restricting Touches 401
Interpreting Touches 402
Gesture Recognizers 408
Distinguishing Gestures Manually 408
Gesture Recognizer Classes 412
Multiple Gesture Recognizers 416
Subclassing Gesture Recognizers 418
Gesture Recognizer Delegate 419
Touch Delivery 422
Table of Contents | xi
Hit-Testing 423
Initial Touch Event Delivery 427
Gesture Recognizer and View 427
Touch Exclusion Logic 429
Recognition 430
Touches and the Responder Chain 431
Part V. Interface
19. View Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
Creating a View Controller 437
Manual View Controller, Manual View 438
Manual View Controller, Nib View 441
Nib-Instantiated View Controller 443
No View 445
Up-Shifted Root View 446
Rotation 447
Initial Orientation 448
Rotation Events 452
Modal Views 453
Modal View Configuration 454
Modal View Presentation 456
Modal View Dismissal 457
Modal Views and Rotation 459
Tab Bar Controllers 461
Tab Bar Item Images 462
Configuring a Tab Bar Controller 463
Navigation Controllers 464
Bar Button Items 466
Configuring a Navigation Interface 468
Navigation Interface Rotation 474
View Controller Lifetime Events 476
View Controller Memory Management 477
20. Scroll Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
Creating a Scroll View 482
Scrolling 484
Paging 487
Tiling 488
Zooming 491
Zooming Programmatically 493
Zooming with Detail 493
xii | Table of Contents
Scroll View Delegate 499
Scroll View Touches 500
Scroll View Performance 503
21. Table Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
Table View Cells 507
Built-In Cell Styles 508
Custom Cells 512
Table View Data 517
The Three Big Questions 518
Table View Sections 521
Refreshing Table View Data 524
Variable Row Heights 526
Table View Selection 528
Table View Scrolling and Layout 533
Table View Searching 533
Table View Editing 539
Deleting Table Items 541
Editable Content in Table Items 543
Inserting Table Items 544
Rearranging Table Items 546
22. Popovers and Split Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
Presenting a Popover 550
Managing a Popover 553
Dismissing a Popover 554
Automatic Popovers 557
Split Views 558
23. Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
UILabel 564
UITextField 565
Editing and the Keyboard 568
Configuring the Keyboard 572
Text Field Delegate and Control Event Messages 572
The Text Field Menu 574
UITextView 576
Core Text 579
24. Web Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
Loading Content 588
Communicating with a Web View 593
Table of Contents | xiii
25. Controls and Other Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
UIActivityIndicatorView 597
UIProgressView 598
UIPickerView 600
UISearchBar 602
UIControl 604
UISwitch 605
UIPageControl 605
UIDatePicker 606
UISlider 609
UISegmentedControl 612
UIButton 614
Custom Controls 617
Bars 620
UINavigationBar 621
UIToolbar 623
UITabBar 623
26. Modal Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Alert View 630
Action Sheet 631
Dialog Alternatives 635
Local Notifications 636
Part VI. Some Frameworks
27. Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
System Sounds 643
Audio Session 644
Audio Player 648
Remote Control of Your Sound 650
Playing Sound in the Background 651
Further Topics in Sound 653
28. Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
MPMoviePlayerController 656
MPMoviePlayerViewController 660
UIVideoEditorController 661
Further Topics in Video 662
29. Music Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
Exploring the Music Library 667
xiv | Table of Contents
The Music Player 671
The Music Picker 675
30. Photo Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
UIImagePickerController 679
Choosing from the Photo Library 680
Using the Camera 681
The Assets Library Framework 684
31. Address Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
Address Book Database 687
Address Book Interface 690
ABPeoplePickerNavigationController 690
ABPersonViewController 692
ABNewPersonViewController 692
ABUnknownPersonViewController 693
32. Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
Calendar Database 695
Calendar Interface 700
33. Mail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
Mail Message 703
SMS Message 704
34. Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
Presenting a Map 705
Annotations 706
Overlays 712
35. Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
Location 717
Heading and Course 719
Acceleration 720
Shake Events 721
UIAccelerometer 722
Core Motion 725
Table of Contents | xv
Part VII. Final Topics
36. Persistent Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
The Sandbox 729
Basic File Operations 730
Saving and Reading Files 731
User Defaults 733
File Sharing 735
Document Types 735
Handing Off a Document 737
XML 740
SQLite 746
Image File Formats 747
37. Basic Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
HTTP Requests 751
Bonjour 757
Push Notifications 759
Beyond Basic Networking 760
38. Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761
The Main Thread 761
Why Threading Is Hard 764
Three Ways of Threading 765
Manual Threads 766
NSOperation 768
Grand Central Dispatch 772
Threads and App Backgrounding 775
39. Undo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
The Undo Manager 779
The Undo Interface 782
The Undo Architecture 785
40. Epilogue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
xvi | Table of Contents
Preface
Aut lego vel scribo; doceo scrutorve sophian.
—Sedulius Scottus
With the advent of version 2 of the iPhone system, Apple proved they could do a re-
markable thing — adapt their existing Cocoa computer application programming
framework to make applications for a touch-based device with limited memory and
speed and a dauntingly tiny display. The resulting Cocoa Touch framework, in fact,
turned out to be in many ways better than the original Cocoa.
A programming framework has a kind of personality, an overall flavor that provides an
insight into the goals and mindset of those who created it. When I first encountered
Cocoa Touch, my assessment of its personality was: “Wow, the people who wrote this
are really clever!” On the one hand, the number of built-in interface widgets was se-
verely and deliberately limited; on the other hand, the power and flexibility of some of
those widgets, especially such things as UITableView, was greatly enhanced over their
Mac OS X counterparts. Even more important, Apple created a particularly brilliant
way (UIViewController) to help the programmer make entire blocks of interface come
and go and supplant one another in a controlled, hierarchical manner, thus allowing
that tiny iPhone display to unfold virtually into multiple interface worlds within a single
app without the user becoming lost or confused.
Even more impressive, Apple took the opportunity to recreate and rationalize Cocoa
from the ground up as Cocoa Touch. Cocoa itself is very old, having begun life as
NeXTStep before Mac OS X even existed. It has grown by accretion and with a certain
conservatism in order to maintain something like backward compatibility. With Cocoa
Touch, on the other hand, Apple had the opportunity to throw out the baby with the
bath water, and they seized this opportunity with both hands.
So, although Cocoa Touch is conceptually based on Mac OS X Cocoa, it is very clearly
not Mac OS X Cocoa, nor is it limited or defined by Mac OS X Cocoa. It’s an inde-
pendent creature, a leaner, meaner, smarter Cocoa. I could praise Cocoa Touch’s de-
liberate use of systematization (and its healthy respect for Occam’s Razor) through
numerous examples. Where Mac OS X’s animation layers are glommed onto views as
a kind of afterthought, a Cocoa Touch view always has an animation layer counterpart.
xvii
Memory management policies, such as how top-level objects are managed when a nib
loads, are simplified and clarified. And so on.
At the same time, Cocoa Touch is still a form of Cocoa. It still requires a knowledge of
Objective-C. It is not a scripting language; it is certainly not aimed at nonprogrammers,
like HyperCard’s HyperTalk or Apple’s AppleScript. It is still huge and complicated.
In fact, it’s rather difficult.
Meanwhile, Cocoa Touch itself evolves and changes. The iPhone System 2 matured
into the iPhone System 3. Then there was a sudden sally in a new direction when the
iPad introduced a larger screen and iPhone System 3.2. The iPhone 4 and its double-
resolution Retina display also ran on a major system increment, now dubbed iOS 4.
Every one of these changes has brought new complexities for the programmer to deal
with. To give just one simple example, users rightly complained that switching between
apps on the iPhone meant quitting one app and launching another. So Apple gave the
iPhone 4 the power of multitasking; the user can switch away from an app and then
return to it later to find it still running and in the state it was left previously. All well
and good, but now programmers must scurry to make their apps compatible with mul-
titasking, which is not at all trivial.
The popularity of the iPhone, with its largely free or very inexpensive apps, and the
subsequent popularity of the iPad, have brought and will continue to bring into the
fold many new programmers who see programming for these devices as worthwhile
and doable, even though they may not have felt the same way about Mac OS X. Apple’s
own annual WWDC developer conventions have reflected this trend, with their em-
phasis shifted from Mac OS X to iOS instruction.
The widespread eagerness to program iOS, however, though delightful on the one
hand, has also fostered a certain tendency to try to run without first learning to walk.
iOS gives the programmer mighty powers that can seem as limitless as imagination
itself, but it also has fundamentals. I often see questions online from programmers who
are evidently deep into the creation of some interesting app, but who are stymied in a
way that reveals quite clearly that they are unfamiliar with the basics of the very world
in which they are so happily cavorting.
It is this state of affairs that has motivated me to write this book, which is intended to
ground the reader in the fundamentals of iOS. I love Cocoa and have long wished to
write about it, but it is iOS and its popularity that has given me a proximate excuse to
do so. Indeed, my working title was “Fundamentals of Cocoa Touch Programming.”
HereIhaveattemptedtomarshalandexpound,inwhatIhopeisapedagogicallyhelpful
and instructive yet ruthlessly Euclidean and logical order, the principles on which
sound iOS programming rests, including a good basic knowledge of Objective-C (start-
ing with C itself) and the nature of object-oriented programming, advice on the use of
the tools, the full story on how Cocoa objects are instantiated, referred to, put in com-
munication with one another, and managed over their lifetimes, and a survey of the
primary interface widgets and other common tasks. My hope, as with my previous
xviii | Preface
books, is that you will both read this book cover to cover (learning something new often
enough to keep you turning the pages) and keep it by you as a handy reference.
This book is not intended to disparage Apple’s own documentation and example
projects. They are wonderful resources and have become more wonderful as time goes
on. I have depended heavily on them in the preparation of this book. But I also find
that they don’t fulfill the same function as a reasoned, ordered presentation of the facts.
The online documentation must make assumptions as to how much you already know;
it can’t guarantee that you’ll approach it in a given order. And online documentation
is more suitable to reference than to instruction. A fully written example, no matter
how well commented, is difficult to follow; it demonstrates, but it does not teach.
A book, on the other hand, has numbered chapters and sequential pages; I can assume
you know C before you know Objective-C for the simple reason that Chapter 1 precedes
Chapter 2. And along with facts, I also bring to the table a degree of experience, which
I try to communicate to you. Throughout this book you’ll see me referring to “common
beginner mistakes”; in most cases, these are mistakes that I have made myself, in ad-
dition to seeing others make them. I try to tell you what the pitfalls are because I assume
that, in the course of things, you will otherwise fall into them just as naturally as I did
as I was learning. You’ll also see me construct many examples piece by piece or extract
and explain just one tiny portion of a larger app. It is not a massive finished program
that teaches programming, but an exposition of the thought process that developed
that program. It is this thought process, more than anything else, that I hope you will
gain from reading this book.
iOS is huge, massive, immense. It’s far too big to be encompassed in a book even of
this size. And in any case, that would be inappropriate and unnecessary. There are
entire areas of Cocoa Touch that I have ruthlessly avoided discussing. Some of them
would require an entire book of their own. Others you can pick up well enough, when
the time comes, from the documentation. This book is only a beginning — the funda-
mentals. But I hope that it will be the firm foundation that will make it easier for you
to tackle whatever lies beyond, in your own fun and rewarding iOS programming fu-
ture.
In closing, some version numbers, so that you know what assumptions I am making.
At the time I started writing this book, system versions 3.1.3 (on the iPhone) and 3.2
(on the iPad) were most recent. As I was working on the book, iOS 4 and the iPhone 4
came into being, but it didn’t yet run on the iPad. Subsequently iOS 4.2 emerged: the
first system able to run on both the iPhone and the iPad. At the same time, Xcode was
improved up to 3.2.5.
Then, just in time for my final revisions, Xcode 3.2.6 and iOS 4.3 were released, along
withthefirstpublicversionofthelong-awaitedXcode4.Xcode4isathoroughoverhaul
of the IDE: menus, windows, and preferences are quite different from Xcode 3.2.x. At
the same time, both Xcode 4 and Xcode 3.2.x can coexist on the same machine and
can be used to work on the same project; moreover, Xcode 3.2.x has some specialized
Preface | xix
capabilities that Xcode 4 lacks, so some long-standing developers may well continue
to use it. This situation presents a dilemma for an author describing the development
process. However, for iOS programming, I recommend adoption of Xcode 4, and this
book assumes that you have adopted it.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter-
mined by context.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
xx | Preface
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “Programming iOS 4 by Matt Neuburg
(O’Reilly). Copyright 2011 Matt Neuburg, 978-1-449-38843-0.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at permissions@oreilly.com.
Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easily
search over 7,500 technology and creative reference books and videos to
find the answers you need quickly.
Withasubscription,youcanreadanypageandwatchanyvideofromourlibraryonline.
Read books on your cell phone and mobile devices. Access new titles before they are
available for print, and get exclusive access to manuscripts in development and post
feedback for the authors. Copy and paste code samples, organize your favorites, down-
load chapters, bookmark key sections, create notes, print out pages, and benefit from
tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have full
digital access to this book and others on similar topics from O’Reilly and other pub-
lishers, sign up for free at http://my.safaribooksonline.com.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
http://oreilly.com/catalog/0636920010258/
To comment or ask technical questions about this book, send email to:
bookquestions@oreilly.com
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Preface | xxi
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
It’s a poor craftsman who blames his tools. No blame attaches to the really great tools
by which I have been assisted in the writing of this book. I am particularly grateful to
the Unicomp Model M keyboard (http://pckeyboard.com), without which I could not
have produced so large a book so painlessly. I was also aided by wonderful software,
including TextMate (http://macromates.com) and AsciiDoc (http://www.methods.co.nz/
asciidoc). BBEdit (http://www.barebones.com) helped with its diff display. Screenshots
were created with Snapz Pro X (http://www.ambrosiasw.com) and GraphicConverter
(http://www.lemkesoft.com); diagrams were drawn with OmniGraffle (http://www.om
nigroup.com).
The splendid O’Reilly production process converted my AsciiDoc text files into PDF
while I worked, allowing me to proofread in simulated book format. Were it not for
this, and the Early Release program that permitted me to provide my readers with
periodic updates of the book as it grew, I would never have agreed to undertake this
project in the first place. I would like particularly to thank Tools maven Abby Fox for
her constant assistance.
I have taken advice from two tech reviewers, Dave Smith and David Rowland, and have
been assisted materially and spiritually by many readers who submitted errata and
encouragement. I was particularly fortunate in having Brian Jepson as editor; he pro-
vided enthusiasm for the O’Reilly tools and the electronic book formats, a watchful
eye, and a trusting attitude; he also endured the role of communications pipeline when
I needed to prod various parts of the O’Reilly machine. I have never written an O’Reilly
book without the help of Nancy Kotary, and I didn’t intend to start now; her sharp eye
has smoothed the bristles of my punctuation-laden style. For errors that remain, I take
responsibility, of course.
xxii | Preface
PART I
Language
Apple has provided a vast toolbox for programming iOS to make an app come to life
and behave the way you want it to. That toolbox is the API (application programming
interface). To use the API, you must speak the API’s language. That language, for the
most part, is Objective-C, which itself is built on top of C; some pieces of the API use
C itself. This part of the book instructs you in the basics of these languages:
• Chapter 1 explains C. In general, you will probably not need to know all the ins
and outs of C, so this chapter restricts itself to those aspects of C that you need to
know in order to use both Objective-C and the C-based areas of the API.
• Objective-C adds object-based programming features to C. Chapter 2 discusses
object-based programming in general architectural terms. It also explains some
extremely important terms that will be used throughout the book, along with the
concepts that lie behind them.
• Chapter 3 introduces the basic syntax of Objective-C.
• Chapter 4 continues the explanation of Objective-C, discussing the nature of
Objective-C classes, with emphasis on how to create a class in code.
• Chapter 5 completes the introduction to Objective-C, discussing how instances
are created and initialized, along with an explanation of such related topics as
polymorphism, instance variables, accessors, self and super, key–value coding,
and properties.
Even at this point, our discussion of Objective-C is not yet complete; we’ll return in
Part III to a description of further aspects of the language: those that are particularly
bound up with the Cocoa frameworks.
CHAPTER 1
Just Enough C
Do you believe in C? Do you believe in anything that has
to do with me?
—Leonard Bernstein and Stephen Schwartz, Mass
To program for iOS, you need some knowledge of the C programming language, for
two reasons:
• Most of your iOS programming will be in the Objective-C language, and Objective-
C is a superset of C. This means that Objective-C presupposes C; everything that
is true of C trickles up to Objective-C. A common mistake is to forget that
“Objective-C is C” and to neglect a basic understanding of C.
• Some of the iOS API involves C rather than Objective-C. Even in Objective-C code,
you often need to use C data structures and C function calls. For example, a rec-
tangle is represented as a CGRect, which is a C struct, and to create a CGRect from
four numbers you call CGRectMake, which is a C function. The iOS API docu-
mentation will very often show you C expressions and expect you to understand
them.
The best way to learn C is to read The C Programming Language (PTR Prentice Hall,
1988) by Brian W. Kernighan and Dennis M. Ritchie, commonly called K&R (Ritchie
was the creator of C). It is one of the best computer books ever written: brief, dense,
and stunningly precise and clear. K&R is so important for effective iOS (and Mac OS
X) programming that I keep a physical copy beside me at all times while coding, and I
recommend that you do the same. Another useful manual is The C Book, by Mike
Banahan, Declan Brady and Mark Doran, available online at http://publications.gbdirect
.co.uk/c_book/.
You don’t have to know all about C in order to use Objective-C effectively, though;
and that’s a good thing. C is not a large or difficult language, but it has some tricky
corners and can be extremely subtle, powerful, and low-level. Also, it would be im-
possible, and unnecessary, for me to describe all of C in a single chapter. C is described
far more fully and correctly in K&R, The C Book, and elsewhere than I could possibly
3
do it. Sooner or later, you’re probably going to have technical questions about C that
this chapter doesn’t (and shouldn’t) make any attempt to answer. So I emphasize that
you really, really ought to have K&R or something similar at hand and resort to it as
needed.
What I can do, and what this chapter will attempt to do, is tell you what aspects of C
are important to understand at the outset, before you even start using Objective-C for
iOS programming. That’s why this chapter is “Just Enough C”: it’s just enough to get
you going, comfortably and safely.
If you know no C at all, I suggest that, as an accompaniment to this chapter, you also
read parts of K&R (think of this as “C: The Good Parts Version”). Here’s my proposed
K&R syllabus:
• Quickly skim K&R Chapter 1, the tutorial.
• Carefully read K&R Chapters 2 through 4.
• Read the first three sections of K&R Chapter 5 on pointers and arrays. You don’t
need to read the rest of Chapter 5 because you won’t typically be doing any pointer
arithmetic, but you do need to understand clearly what a pointer is, as Objective-
C is all about objects and every reference to an object is a pointer; you’ll be seeing
and using that * character constantly.
• Read also the first section of K&R Chapter 6, on structures (structs); as a beginner,
you probably won’t define any structs, but you will use them quite a lot, so you’ll
need to know the notation (for example, as I’ve already said, a CGRect is a struct).
• Glance over K&R Appendix B, which covers the standard library, because you may
find yourself making certain standard library calls, such as the mathematical func-
tions; forgetting that the library exists is a typical beginner mistake.
Just to make things a little more confusing, the C defined in K&R is not precisely the
C that forms the basis of Objective-C. Developments subsequent to K&R have resulted
in further C standards (ANSI C, C89, C99), and the Xcode compiler extends the C
language in its own ways. By default, Xcode projects are treated as C99 (though you
could specify another C standard if you really wanted to). Fortunately, the most im-
portant differences between K&R’s C and Xcode’s C are small, convenient improve-
ments that are easily remembered, so K&R remains the best and most reliable C ref-
erence.
Compilation, Statements, and Comments
C is a compiled language. You write your program as text; to run the program, things
proceed in two stages. First your text is compiled into machine instructions; then those
machine instructions are executed. Thus, as with any compiled language, you can make
two kinds of mistake:
4 | Chapter 1: Just Enough C
• Any purely syntactic errors (meaning that you spoke the C language incorrectly)
will be caught by the compiler, and the program won’t even begin to run.
• If your program gets past the compiler, then it will run, but there is no guarantee
that you haven’t made some other sort of mistake, which can be detected only by
noticing that the program doesn’t behave as intended.
The C compiler is fussy, but you should accept its interference with good grace. The
compiler is your friend: learn to love it. It may emit what looks like an irrelevant or
incomprehensible error message, but when it does, the fact is that you’ve done some-
thing wrong and the compiler has helpfully caught it for you. Also, the compiler can
warn you if something seems like a possible mistake, even though it isn’t strictly illegal;
these warnings, which differ from outright errors, are also helpful and should not be
ignored.
I have said that running a program requires a preceding stage: compilation. But in fact
there is a third stage that precedes compilation: preprocessing. (It doesn’t really matter
whether you think of preprocessing as a stage preceding compilation or as the first stage
of compilation.) Preprocessing modifies your text, so when your text is handed to the
compiler, it is not identical to the text you wrote. Preprocessing might sound tricky and
intrusive, but in fact it proceeds only according to your instructions and is helpful for
making your code clearer and more compact.
C is a statement-based language; every statement ends in a semicolon. (Forgetting the
semicolon is a common beginner’s mistake and is liable to get you a completely irrel-
evant and incomprehensible error message from the compiler.) For readability, pro-
grams are mostly written with one statement per line, but this is by no means a hard
and fast rule: long statements (which, unfortunately, arise very commonly because of
Objective-C’s verbosity) are commonly split over multiple lines, and extremely short
statements are sometimes written two or three to a line. You cannot split a line just
anywhere, however; for example, a literal string can’t contain a return character. In-
dentation is linguistically meaningless and is purely a matter of convention (and C
programmers argue over those conventions with near-religious fervor); Xcode helps
“intelligently” by indenting automatically, and you can use its automatic indentation
both to keep your code readable and to confirm that you’re not making any basic
syntactic mistakes.
Comments are delimited in K&R C by /* ... */; the material between the delimiters
can consist of multiple lines (K&R 1.2). In modern versions of C, a comment also can
be denoted by two slashes (//); the rule is that if two slashes appear, they and everything
after them on the same line are ignored:
int lower = 0; // lower limit of temperature table
These are sometimes called C++-style comments and are much more convenient for
brief comments than the K&R comment syntax.
Compilation, Statements, and Comments | 5
Throughout the C language (and therefore, throughout Objective-C as well), capitali-
zation matters. All names are case-sensitive. There is no such data type as Int; it’s
lowercase “int.” If you declare an int called lower and then try to speak of the same
variable as Lower, the compiler will complain. By convention, variable names tend to
start with a lowercase letter.
Variable Declaration, Initialization, and Data Types
C is a strongly typed language. Every variable must be declared, indicating its data type,
before it can be used. Declaration can also involve explicit initialization; a variable that
is declared but not explicitly initialized is of uncertain value (and should be regarded
as dangerous until it is initialized). In K&R C, declarations must precede all other
statements, but in modern versions of C, this rule is relaxed so that you don’t have to
declare a variable until just before you start using it. The usual convention is thus to
declare a variable and assign it a value as it makes its first appearance on the scene:
int height = 2;
int width = height * 2;
height = height + 1;
int area = height * width;
The basic built-in C data types are all numeric: char (one byte), int (four bytes), float
and double (floating-point numbers), and varieties such as short (short integer), long
(long integer), unsigned short, and so on. iOS makes use of some further numeric types
derived from the C numeric types (by way of the typedef statement, K&R 6.7); the most
important of these are NSInteger (along with NSUInteger) and CGFloat. You don’t
Choosing a Compiler
The compiler situation in Xcode is rather complicated. Originally, Xcode’s compiler
was the free open source GCC (http://gcc.gnu.org). More recently, Xcode has been
phasing in use of another free open source compiler, LLVM (http://llvm.org). Changing
compilers is scary, so Apple has proceeded in stages, as follows:
• GCC is still supported.
• A hybrid compiler, LLVM-GCC, provides the advantages of LLVM compilation,
but the code is parsed with GCC for maximum backward compatibility.
• A pure LLVM compiler (also referred to as Clang) does its own parsing and pro-
vides more intelligent and helpful error messages and warnings.
As Xcode 3.2.x evolved, LLVM-GCC was eventually considered the best choice, but
Apple was hesitant to make it the default compiler, so GCC remained the default. In
Xcode 4, LLVM-GCC is the default compiler; both GCC and the pure LLVM compiler
are also available. (The choice of compiler is a project-level build setting; seeChapter 6.)
6 | Chapter 1: Just Enough C
need to use these explicitly unless an API tells you to, and even when you do, just think
of NSInteger as int and CGFloat as float, and you’ll be fine.
To cast (or typecast) a variable’s value explicitly to another type, precede the variable’s
name with the other type’s name in parentheses:
int height = 2;
float fheight = (float)height;
In that particular example, the explicit cast is unnecessary because the integer value
will be cast to a float implicitly as it is assigned to a float variable, but it illustrates the
notation. You’ll find yourself typecasting quite a bit in Objective-C, mostly in order to
subdue the worries of the compiler (examples appear in Chapter 3).
Another form of numeric initialization is the enum (K&R 2.3). It’s a way of assigning
names to a sequence of numeric values and is useful when a value represents one of
several possible options. The Cocoa API uses this device a lot. For example, the three
possible types of status bar animation are defined like this:
typedef enum {
UIStatusBarAnimationNone,
UIStatusBarAnimationFade,
UIStatusBarAnimationSlide,
} UIStatusBarAnimation;
That definition assigns the value 0 to the name UIStatusBarAnimationNone, the value 1
to the name UIStatusBarAnimationFade, and the value 2 to the name UIStatusBar-
AnimationSlide. The upshot is, however, that you can use the suggestively meaningful
names without caring about, or even knowing, the arbitrary numeric values they rep-
resent. It’s a useful idiom, and you may well have reason to define enums in your own
code.
There appears to be a native text type (a string) in C, but this is something of an illusion;
behind the scenes, it is actually a null-terminated array of char. For example, in C you
can write a string literal like this:
"string"
But in fact this is stored as 7 bytes, the numeric (ASCII) equivalents of each letter
followed by a byte consisting of 0 to signal the end of the string. This data structure,
called a C string, is rather tricky, and if you’re lucky you’ll rarely or never encounter
one while programming iOS. In general, when working with strings, you’ll use an
Objective-C object type called NSString. An NSString is totally different from a C string;
it happens, however, that Objective-C lets you write a literal NSString in a way that
looks very like a C string:
@"string"
Notice the at-sign! This expression is actually a directive to the Objective-C compiler
to form an NSString object. A common mistake is forgetting the at-sign, thus causing
your expression to be interpreted as a C string, which is a completely different animal.
Variable Declaration, Initialization, and Data Types | 7
Because the notation for literal NSStrings is modeled on the notation for C strings, it
is worth knowing something about C strings, even though you won’t generally en-
counter them. For example, K&R lists a number of escaped characters (K&R 2.3),
which you can also use in a literal NSString, including the following:
n
A Unix newline character
t
A tab character
"
A quotation mark (escaped to show that this is not the end of the string literal)

A backslash
NSStrings are natively Unicode-based, but because Objective-C is C,
including non-ASCII characters in a literal NSString was, until quite
recently, remarkably tricky, and you needed to know about such things
as the x and u escape sequences. Now, however, it is perfectly legal to
type a bullet or any other non-ASCII character directly into an NSString
literal, and you should ignore old Internet postings (and even an occa-
sional sentence in Apple’s own documentation) warning that it is not.
K&R also mention a notation for concatenating string literals, in which multiple string
literals separated only by white space are automatically concatenated and treated as a
single string literal. This notation is useful for splitting a long string into multiple lines
for legibility, and Objective-C copies this convention for literal NSStrings as well, ex-
cept that you have to remember the at-sign:
@"This is a big long literal string "
@"which I have broken over two lines of code.";
Structs
C offers few simple native data types, so how are more complex data types made? There
are three ways: structures, pointers, and arrays. Both structures and pointers are going
tobecrucialwhenyou’reprogrammingiOS.You’relesslikelytoneedaCarray,because
Objective-C has its own NSArray object type, but it will arise in a couple of examples
later in this book.
A C structure, usually called a struct (K&R 6.1), is a compound data type: it combines
multiple data types into a single type, which can be passed around as a single entity.
Moreover, the elements constituting the compound entity have names and can be ac-
cessed by those names through the compound entity, using dot-notation. For example,
the iOS documentation tells you that a CGPoint is defined as follows:
8 | Chapter 1: Just Enough C
struct CGPoint {
CGFloat x;
CGFloat y;
};
typedef struct CGPoint CGPoint;
Recall that a CGFloat is basically a float, so this is a compound data type made up of
two simple native data types; in effect, a CGPoint has two CGFloat parts, and their
names are x and y. (The rather odd-looking last line merely asserts that one can use the
term CGPoint instead of the more verbose struct CGPoint.) So we can write:
CGPoint myPoint;
myPoint.x = 4.3;
myPoint.y = 7.1;
Just as we can assign to myPoint.x in order to set this part of the struct, we can say my-
Point.x to get this part of the struct. It’s as if myPoint.x were the name of a variable.
Moreover, an element of a struct can itself be a struct, and the dot-notation can be
chained. To illustrate, first note the existence of another iOS struct, CGSize:
struct CGSize {
CGFloat width;
CGFloat height;
};
typedef struct CGSize CGSize;
Put a CGPoint and a CGSize together and you’ve got a CGRect:
struct CGRect {
CGPoint origin;
CGSize size;
};
typedef struct CGRect CGRect;
So suppose we’ve got a CGRect variable called myRect, already initialized. Then my-
Rect.origin is a CGPoint, and myRect.origin.x is a CGFloat. Similarly, myRect.size is
a CGSize, and myRect.size.width is a CGFloat. You could change just the width part
of our CGRect directly, like this:
myRect.size.width = 8.6;
Instead of initializing a struct by assigning to each of its elements, you can initialize it
at declaration time by assigning values for all its elements at once, in curly braces,
separated by commas, like this:
CGPoint myPoint = { 4.3, 7.1 };
The iOS API has many commonly used structs, typically accompanied by convenience
functions for working with them.
Structs | 9
Pointers
The other big way that C extends its range of data types is by means of pointers (K&R
5.1). A pointer is an integer (of some size or other) with a meaning: it designates the
location in memory where the real data is to be found. Knowing the structure of that
data and how to work with it, as well as allocating a block of memory of the required
size beforehand and disposing of that block of memory when it’s no longer needed, is
a very complicated business. Luckily, this is exactly the sort of complicated business
that Objective-C is going to take care of for us. So all you really have to know in order
to use pointers is what they are and what notation is used to refer to them.
Let’s start with a simple declaration. If we wanted to declare an integer in C, we could
say:
int i;
That line says, “i is an integer.” Now let’s instead declare a pointer to an integer:
int* intPtr;
That line says, “intPtr is a pointer to an integer.” Never mind how we know there really
is going to be an integer at the address designated by this point; here, I’m concerned
only with the notation. It is permitted to place the asterisk in the declaration before the
name rather than after the type:
int *intPtr;
I don’t generally use that second form when declaring a pointer, but it does come in
handy when declaring several variables of the same type in a single statement. Here’s
what I mean. It is legal, though I did not mention this earlier, to declare multiple var-
iables of a single type in one statement, like this:
int i, j, k;
By the same token, it is possible to declare multiple pointers to the same type in one
statement by attaching the asterisk to the variable name (repeatedly):
int *intPtr1, *intPtr2, *intPtr3;
However, the name of the type is still int*. If you are asked what type is intPtr is, the
answer is int* (a pointer to an int); the asterisk is part of the name of the type of this
variable. If you needed to cast a variable p to this type, you’d cast like this: (int*)p.
Pointers are very important in Objective-C, because Objective-C is all about objects
(Chapter 2), and every variable referring to an object is itself a pointer. For example,
I’ve already mentioned that the Objective-C string type is called NSString. So the way
to declare an NSString variable is as a pointer to an NSString:
NSString* s;
An NSString literal is an NSString value, so we can even declare and initialize this
NSString object, thus writing a seriously useful line of Objective-C code:
10 | Chapter 1: Just Enough C
NSString* s = @"Hello, world!";
In pure C, having declared a pointer-to-integer called intPtr, you are liable to speak
later in your code of *intPtr. This notation, outside of a declaration, means “the thing
pointed to by the pointer intPtr.” You speak of *intPtr because you wish to access the
integer at the far end of the pointer.
But in Objective-C, this is generally not the case. In your code, you’ll be treating the
pointer to an object as the object. So, for example, having declared s as a pointer to an
NSString, you will not then proceed to speak of *s; rather, you will speak simply of s,
as if it were the string. All the Objective-C stuff you’ll want to do with an object will
expect the pointer, not the object at the far end of the pointer; behind the scenes,
Objective-C itself will take care of the messy business of following the pointer to its
block of memory and doing whatever needs to be done in that block of memory. This
fact is extremely convenient for you as a programmer, but it does cause Objective-C
users to speak a little loosely; we tend to say that “s is an NSString,” when of course it
is actually a pointer to an NSString.
Youmustneverletthisconveniencelullyouintoforgettingthecrucialfactthatapointer
is a pointer. The logic of how pointers work is different from the logic of how simple
data types work. The difference is particularly evident with assignment. Assignment to
a simple data type changes the data value. Assignment to a pointer repoints the pointer.
Suppose ptr1 and ptr2 are both pointers, and you say:
ptr1 = ptr2;
Now ptr1 and ptr2 are pointing at the same thing. Any change to the thing pointed to
by ptr1 will also change the thing pointed to by ptr2, because they are the same thing.
Meanwhile, whatever ptr1 was pointing to before the assignment is now not being
pointed to by ptr1; it might, indeed, be pointed to by nothing (which could be bad). A
firm understanding of these facts is crucial when working in Objective-C (Figure 1-1).
The most general type of pointer is pointer-to-void (void*), the generic pointer. It is legal
to use a generic pointer wherever a specific type of pointer is expected. In effect, pointer-
to-void casts away type checking as to what’s at the far end of the pointer. Thus, the
following is legal:
int* p1; // and pretend p1 has a value
void* p2;
p2 = p1;
p1 = p2;
Arrays
A C array (K&R 5.3) consists of multiple elements of the same data type. An array
declaration states the data type of the elements, followed by the name of the array,
along with square brackets containing the number of elements:
int arr[3]; // means: arr is an array consisting of 3 ints
Arrays | 11
To refer to an element of an array, use the array’s name followed by the element number
in square brackets. The first element of an array is numbered 0. So we can initialize an
array by assigning values to each element in turn:
int arr[3];
arr[0] = 123;
arr[1] = 456;
arr[2] = 789;
Figure 1-1. Pointers and assignment
12 | Chapter 1: Just Enough C
Alternatively, you can initialize an array at declaration time by assigning a list of values
in curly braces, just as with a struct. In this case, the size of the array can be omitted
from the declaration, because it is implicit in the initialization (K&R 4.9):
int arr[] = {123, 456, 789};
Curiously, the name of an array is the name of a pointer (to the first element of the
array). Thus, for example, having declared arr as in the preceding examples, you can
use arr wherever a value of type int* (a pointer to an int) is expected. This fact is the
basis of some highly sophisticated C idioms that you almost certainly won’t need to
know about (which is why I don’t recommend that you read any of K&R Chapter 5
beyond section 3).
C arrays rarely arise in practice when programming iOS, because you’ll work mostly
with the NSArray object type instead. But here’s a case where they do. The function
CGContextStrokeLineSegments is declared like this:
void CGContextStrokeLineSegments (
CGContextRef c,
const CGPoint points[],
size_t count
);
The second parameter is an array (meaning a C array) of CGPoints. That’s what the
square brackets tell you. So to call this function, you’d need to know at least how to
make an array of CGPoints. You might do it like this:
CGPoint arr[] = {{4,5}, {6,7}, {8,9}, {10,11}};
Having done that, you can pass arr as the second argument in a call to CGContextStroke-
LineSegments.
Also, a C string, as I’ve already mentioned, is actually an array. For example, the
NSString method stringWithUTF8String: takes (according to the documentation) “a
NULL-terminated C array of bytes in UTF8 encoding;” but the parameter is declared
not as an array, but as a char*. Those are the same thing, and are both ways of saying
that this method takes a C string.
Operators
Arithmetic operators are straightforward (K&R 2.5), but watch out for the rule that
“integer division truncates any fractional part.” This rule is the cause of much novice
error in C. If you have two integers and you want to divide them in such a way as to
get a fractional result, you must represent at least one of them as a float:
int i = 3;
float f = i/2; // beware! not 1.5
To get 1.5, you should have written i/2.0 or (float)i/2.
Operators | 13
The integer increment and decrement operators (K&R 2.8), ++ and --, work differently
dependingonwhethertheyprecedeorfollowtheirvariable.Theexpression++i replaces
the value of i by 1 more than its current value and then uses the resulting value; the
expression i++ uses the current value of i and then replaces it with 1 more than its
current value. This is one of C’s coolest features.
C also provides bitwise operators (K&R 2.9), such as bitwise-and (&) and bitwise-or
(|); they operate on the individual binary bits that constitute integers. Of these, the one
you are most likely to need is bitwise-or, because the Cocoa API often uses bits as
switches when multiple options are to be specified simultaneously. For example, there
are various ways in which a UIView can be resized automatically as its superview is
resized, and you’re supposed to provide one or more of these when setting a UIView’s
autoresizingMask property. The autoresizing options are listed in the documentation
as follows:
enum {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;
The << symbol is the left shift operator; the right operand says how many bits to shift
the left operand. So pretend that an NSUInteger is 8 bits (it isn’t, but let’s keep things
simple and short). Then this enum means that the following name–value pairs are
defined (using binary notation for the values):
UIViewAutoresizingNone
00000000
UIViewAutoresizingFlexibleLeftMargin
00000001
UIViewAutoresizingFlexibleWidth
00000010
UIViewAutoresizingFlexibleRightMargin
00000100
UIViewAutoresizingFlexibleTopMargin
00001000
and so on. The reason for this bit-based representation is that these values can be
combined into a single value (a bitmask) that you pass to set the autoresizingMask. All
Cocoa has to do in order to understand your intentions is to look to see which bits in
the value that you pass are set to 1. So, for example, 00001010 would mean that UIView-
14 | Chapter 1: Just Enough C
AutoresizingFlexibleTopMargin and UIViewAutoresizingFlexibleWidth are true (and
that the others, by implication, are all false).
The question is how to form the value 00001010 in order to pass it. You could just do
the math, figure out that binary 00001010 is decimal 10, and set the autoresizingMask
property to 10, but that’s not what you’re supposed to do, and it’s not a very good idea,
because it’s error-prone and makes your code incomprehensible. Instead, use the
bitwise-or operator to combine the desired options:
myView.autoresizingMask =
UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
This notation works because the bitwise-or operator combines its operands by setting
in the result any bits that are set in either of the operands, so 00001000 | 00000010 is
00001010, which is just the value we’re trying to convey.
Simple assignment (K&R 2.10) is by the equal sign. But there are also compound as-
signment operators that combine assignment with some other operation. For example:
height *= 2; // same as saying: height = height * 2;
The ternary operator (?:) is a way of specifying one of two values depending on a
condition (K&R 2.11). The scheme is as follows:
(condition) ? exp1 : exp2
If the condition is true (see the next section for what that means), the expression exp1
is evaluated and the result is used; otherwise, the expression exp2 is evaluated and the
result is used. For example, you might use the ternary operator while performing an
assignment, using this schema:
myVariable = (condition) ? exp1 : exp2;
What gets assigned to myVariable depends on the truth value of the condition. There’s
nothing happening here that couldn’t be accomplished more verbosely with flow con-
trol (see the next section), but the ternary operator can greatly improve clarity, and I
use it a lot.
Flow Control and Conditions
Basic flow control is fairly simple and usually involves a condition in parentheses and
a block of conditionally executed code in curly braces. These curly braces constitute a
new scope, into which new variables can be introduced. So, for example:
if (x == 7) {
int i = 0;
i += 1;
}
After the closing curly brace in the fourth line, the i introduced in the second line has
ceased to exist, because its scope is the inside of the curly braces. If the contents of the
curly braces consist of a single statement, the curly braces can be omitted, but I would
Flow Control and Conditions | 15
advise beginners against this shorthand, as you can confuse yourself. A common be-
ginner mistake (which will be caught by the compiler) is forgetting the parentheses
around the condition. The full set of flow control statements is given in K&R Chapter
3, and I’ll just summarize them schematically here (Example 1-1).
Example 1-1. The C flow control constructs
if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
else if (condition) {
statements;
} else {
statements;
}
while (condition) {
statements;
}
do {
statements;
} while (condition);
for (before-all; condition; after-each) {
statements;
}
The if...else if...else structure can have as many else if blocks as needed, and
the else block is optional. Instead of an extended if...else if...else if...else
structure, when the conditions would consist of comparing various values against a
single value, you can use the switch statement; however, I never use it, and I don’t
recommend that you do either, as it is rather confusing and can easily go wrong. See
K&R 3.4 if you’re interested.
The C for loop needs some elaboration for beginners (Example 1-1). The before-all
statement is executed once as the for loop is first encountered and is usually used for
initialization of the counter. The condition is then tested, and if true, the block is exe-
cuted; the condition is usually used to test whether the counter has reached its limit.
The after-each statement is then executed, and is usually used to increment or decre-
ment the counter; the condition is then immediately tested again. Thus, to execute a
block using integer values 1, 2, 3, 4, and 5 for i, the notation is:
16 | Chapter 1: Just Enough C
int i;
for (i = 1; i < 6; i++) {
// ... statements ...
}
The need for a counter intended to exist solely within the for loop is so common that
C99 permits the declaration of the counter as part of the before-all statement; the
declared variable’s scope is then inside the curly braces:
for (int i = 1; i < 6; i++) {
// ... statements ...
}
The for loop is one of the few areas in which Objective-C extends C’s flow-control
syntax. Certain Objective-C objects represent enumerable collections of other objects;
“enumerable” basically means that you can cycle through the collection, and cycling
through a collection is called enumerating the collection. To make enumerating easy,
Objective-C provides a for...in operator, which works like a for loop:
SomeType* oneItem;
for (oneItem in myCollection) {
// ... statements ....
}
On each pass through the loop, the variable oneItem (or whatever you call it) takes on
the next value from within the collection. As with the C99 for loop, oneItem can be
declared in the for statement, limiting its scope to the curly braces:
for (SomeType* oneItem in myCollection) {
// ... statements ....
}
To abort a loop from inside the curly braces, use the break statement. To abort the
current iteration from within the curly braces and proceed to the next iteration, use the
continue statement. In the case of while and do, continue means to perform immediately
the conditional test; in the case of a for loop, continue means to perform immediately
the after-each statement and then the conditional test.
C also has a goto statement that allows you to jump to a named (labeled) line in your
code (K&R 3.8); even though goto is notoriously “considered harmful,” there are sit-
uations in which it is pretty much necessary, especially because C’s flow control is
otherwise so primitive.
It is permissible for a C statement to be compounded of multiple state-
ments, separated by commas, to be executed sequentially. The last of
the multiple statements is the value of the compound statement as a
whole. This construct, for instance, lets you perform some secondary
action before each test of a condition or perform more than one
after-each action (an example appears in Chapter 17).
Flow Control and Conditions | 17
We can now turn to the question of what a condition consists of. C has no separate
boolean type; a condition either evaluates to 0, in which case it is considered false, or
it doesn’t, in which case it is true. Comparisons are performed using the equality and
relational operators (K&R 2.6); for example, == compares for equality, and < compares
for whether the first operand is less than the second. Logical expressions can be com-
bined using the logical-and operator (&&) and the logical-or operator (||); using these
along with parentheses and the not operator (!) you can form complex conditions.
Evaluation of logical-and and logical-or expressions is short-circuited, meaning that if
the left condition settles the question, the right condition is never even evaluated.
Don’t confuse the logical-and operator (&&) and the logical-or operator
(||) with the bitwise-and operator (&) and the bitwise-or operator (|)
discussed earlier. Writing & when you mean && (or vice versa) can result
in surprising behavior.
The operator for testing basic equality, ==, is not a simple equal sign; forgetting the
difference is a common novice mistake. The problem is that such code is legal: simple
assignment, which is what the equal sign means, has a value, and any value is legal in
a condition. So consider this piece of (nonsense) code:
int i = 0;
while (i = 1) {
i = 0;
}
You might think that the while condition tests whether i is 1. You might then think:
i is 0, so the while body will never be performed. Right? Wrong. The while condition
does not test whether i is 1; it assigns 1 to i. The value of that assignment is also 1, so
the condition evaluates to 1, which means true. So the while body is performed. More-
over, even though the while body assigns 0 to i, the condition is then evaluated again
and assigns 1 to i a second time, which means true yet again. And so on, forever; we’ve
written an endless loop, and the program will hang. (And, depending on what compiler
and settings you’re using, you might not even get a warning of trouble ahead.)
C programmers actually revel in the fact that testing for zero and testing for false are
the same thing and use it to create compact conditional expressions, which are con-
sidered elegant and idiomatic. I don’t recommend that you make use of such idioms,
as they can be confusing, but I must admit that even I do occasionally resort to this sort
of thing:
NSString* s = nil;
// ...
if (s) {
// ...
}
The idea of that code is to test whether the NSString object s, between the time it was
declared and the start of the if-block, has been set to an actual string. Because nil is a
18 | Chapter 1: Just Enough C
You’re allowed to say that, but it doesn’t seem to serve much purpose. On the other
hand, the point of a function might be not so much the value it returns as other things
it does as it is executing, so then it might make perfect sense to ignore its result.
The parentheses in a function’s syntax are crucial. Parentheses are how C knows there’s
a function. Parentheses after the function name in the function definition are how C
knows this is a function definition, and they are needed even if this function takes no
parameters. Parentheses after the function name in the function call are how C knows
this is a function call, and they are needed even if this function call supplies no argu-
ments. Using the bare name of a function is possible, because the name is effectively a
kind of variable (and I’ll talk later about why you might want to do that), but it doesn’t
call the function.
Let’s return to the simple C function definition and call that I used as my example
earlier. Suppose we combine that function definition and the call to that function into
a single program:
int square(int i) {
return i * i;
}
int i = square(3);
That is a legal program, but only because the definition of the square function precedes
the call to that function. If we wanted to place the definition of the square function
elsewhere, such as after the call to it, we would need at least to precede the call with a
declaration of the square function (Example 1-2). The declaration looks just like the
first line of the definition, but it is a statement, ending with a semicolon, rather than a
left curly brace.
Example 1-2. Declaring, calling, and defining a function
int square(int i);
int i = square(3);
int square(int i) {
return i * i;
}
The parameter names in the declaration do not have to match the parameter names in
the definition, but all the types (and, of course, the name of the function) must match.
The types constitute the signature of this function. In other words, it does not matter
if the first line, the declaration, is rewritten thus:
int square(int j);
What does matter is that, both in the declaration and in the definition, square is a
function taking one int parameter and returning an int.
In Objective-C, when you’re sending a message to an object (Chapter 2), you won’t
use a function call; you’ll use a method call (Chapter 3). But you will most definitely
use plenty of C function calls as well. For example, earlier we initialized a CGPoint by
setting its x element and its y element and by assigning its elements values in curly
Functions | 21
braces. But what you’ll usually do to make a new CGPoint is to call CGPointMake, which
is declared like this:
CGPoint CGPointMake (
CGFloat x,
CGFloat y
);
Despite its multiple lines and its indentations, this is indeed a C function declaration,
just like the declaration for our simple square function. It says that CGPointMake is a C
function that takes two CGFloat parameters and returns a CGPoint. So now you know
(I hope) that it would be legal (and typical) to write this sort of thing:
CGPoint myPoint = CGPointMake(4.3, 7.1);
Pointer Parameters and the Address Operator
I’ve mentioned several times that your variables referring to Objective-C objects are
going to be pointers:
NSString* s = @"Hello, world!";
Although it is common to speak loosely of s as an NSString (or just as a string), it is
actually an NSString* — a pointer to an NSString. Therefore, when a C function or an
Objective-C method expects an NSString* parameter, there’s no problem, because
that’s exactly what you’ve got. For example, one way to concatenate two NSStrings is
to call the NSString method stringByAppendingString: (that’s not a misprint; the colon
is part of the name), which the documentation tells you is declared as follows:
- (NSString *)stringByAppendingString:(NSString *)aString
The space between the class name and the asterisk is optional, so this declaration is
telling you (after you allow for the Objective-C syntax) that this method expects one
NSString* parameter and returns an NSString*. That’s splendid because those kinds of
pointers are just what you’ve got and just what you want. So this code would be legal:
NSString* s1 = @"Hello, ";
NSString* s2 = @"World!"
NSString* s3 = [s1 stringByAppendingString: s2];
The idea, then, is that although Objective-C is chock-a-block with pointers and aster-
isks, they don’t make things more complicated, as long as you remember that they
are pointers.
Sometimes, however, a function expects as a parameter a pointer to something, but
what you’ve got is not a pointer but the thing itself. Thus, you need a way to create a
pointer to that thing. The solution is the address operator (K&R 5.1), which is an
ampersand before the name of the thing.
For example, there’s an NSString method for reading from a file into an NSString, which
is declared like this:
22 | Chapter 1: Just Enough C
+ (id)stringWithContentsOfFile:(NSString *)path
encoding:(NSStringEncoding)enc
error:(NSError **)error
Now, never mind what an id is, and don’t worry about the Objective-C method dec-
laration syntax. Just consider the types of the parameters. The first one is an
NSString*; that’s no problem, as every reference to an NSString is actually a pointer to
an NSString. An NSStringEncoding turns out to be merely an alias to a primitive data
type, an NSUInteger, so that’s no problem either. But what on earth is an NSError**?
By all logic, it looks like an NSError** should be a pointer to a pointer to an NSError.
And that’s exactly what it is. This method is asking to be passed a pointer to a pointer
to an NSError. Well, it’s easy to declare a pointer to an NSError:
NSError* myError;
But how can we obtain a pointer to that? With the address operator! So our code might
look, schematically, like this:
NSString* myPath = // something or other;
NSStringEncoding myEnc = // something or other;
NSError* myError = nil;
NSString* result = [NSString stringWithContentsOfFile: myPath
encoding: myEnc
error: &myError];
The important thing to notice is the ampersand. Because myError is a pointer to an
NSError, &myError is a pointer to a pointer to an NSError, which is just what we’re
expected to provide. Thus, everything goes swimmingly.
This device lets Cocoa effectively return two results from this method call. It returns a
real result, which we have captured by assigning it to the NSString pointer we’re calling
result. But if there’s an error, it also wants to set the value of another object, an NSError
object; the idea is that you can then study that NSError object to find out what went
wrong. (Perhaps the file wasn’t where you said it was, or it wasn’t stored in the encoding
youclaimeditwas.)BypassingapointertoapointertoanNSError,yougivethemethod
free rein to do that. Before the call to stringWithContentsOfFile:, myError was unini-
tialized; during the call to stringWithContentsOfFile:, Cocoa can, if it likes, repoint
the pointer, thus giving myError an actual value.
So the idea is that you first check result to see whether it’s nil. If it isn’t, fine; it’s the
string you asked for. If it is, you then study the NSError that myError is now pointing
to, to learn what went wrong. This pattern is frequently used in Cocoa.
You can use the address operator to create a pointer to any named variable. A C function
is technically a kind of named variable, so you can even create a pointer to a function!
This is an example of when you’d use the name of the function without the parentheses:
you aren’t calling the function, you’re talking about it. For example, &square is a pointer
to the square function. In Chapter 9, I describe a situation in which this is a useful thing
to do.
Pointer Parameters and the Address Operator | 23
Another operator used in connection with pointers, or when memory must be allocated
dynamically, is sizeof. It may be followed by a type name in parentheses or by a variable
name; a variable name needn’t be in parentheses, but it can be, so most programmers
ignore the distinction and use parentheses routinely, as if sizeof were a function.
For example, the documentation shows the declaration for AudioSessionSetProperty
like this:
OSStatus AudioSessionSetProperty (
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void *inData
);
Never mind what an AudioSessionPropertyID is; it’s merely a value that you obtain
and pass on. UInt32 is one of those derived numeric types I mentioned earlier. The
discussion has already dealt with pointer-to-void and how to derive a pointer using the
address operator. But look at the name of the second parameter; the function is asking
for the size of the thing pointed to by the third parameter. Here’s an actual call to this
function (from Chapter 27):
UInt32 ambi = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(ambi), &ambi);
Files
The little dance of declaring a function before calling it (Example 1-2) may seem rather
absurd, but it is of tremendous importance in the C language, because it is what allows
a C program to be arbitrarily large and complex.
As your program grows, you can divide and organize it into multiple files. This kind of
organization can make a large program much more maintainable — easier to read,
easier to understand, easier to change without accidentally breaking things. A large C
program therefore usually consists of two kinds of file: code files, whose filename ex-
tension is .c, and header files, whose filename extension is .h. The build system will
automatically “see” all the files and will know that together they constitute a single
program, but there is also a rule in C that code inside one file cannot “see” another file
unless it is explicitly told to do so. Thus, a file itself constitutes a scope; this is a delib-
erate and valuable feature of C, because it helps you keep things nicely pigeonholed.
The way you tell a C file to “see” another file is with the #include directive. The hash
sign in the term #include is a signal that this line is an instruction to the preproces-
sor. In this case, the word #include is followed by the name of another file, and the
directive means that the preprocessor should simply replace the directive by the entire
contents of the file that’s named.
So the strategy for constructing a large C program is something like this:
24 | Chapter 1: Just Enough C
• In each .c file, put the code that only this file needs to know about; typically, each
file’s code consists of related functionality.
• In each .h file, put the function declarations that multiple .c files might need to
know about.
• Have each .c file include those .h files containing the declarations it needs to know
about.
So, for example, if function1 is defined in file1.c, but file2.c might need to call
function1, the declaration for function1 can go in file1.h. Now file1.c can include
file1.h, so all of its functions, regardless of order, can call function1, and file2.c can also
include file1.h, so all of its functions can call function1 (Figure 1-2). In short, header
files are a way of letting code files share knowledge about one another without actually
sharing code (because, if they did share code, that would violate the entire point of
keeping the code in separate files).
But how does the compiler know where, among all these multiple .c files, to begin
execution? Every real C program contains, somewhere, exactly one function called
main, and this is always the entry point for the program as a whole: the compiler sets
things up so that when the program executes, main is called.
The organization for large C programs that I’ve just described will also be, in effect, the
organization for your iOS programs. (The chief difference will be that instead of .c files,
you’ll use .m files, because .m is the conventional filename extension for telling Xcode
that your files are written in Objective-C, not pure C.) Moreover, if you look at any iOS
Xcode project, you’ll discover that it contains a file called main.m; and if you look at
that file, you’ll find that it contains a function called main. That’s the entry point to
your application’s code when it runs.
Figure 1-2. How a large C program is divided into files
Files | 25
Furthermore, your iOS programs consist not only of your code files and their corre-
sponding .h files, but also of Apple’s code files and their corresponding .h files. The
difference is that Apple’s code files (which are what constitutes Cocoa) have already
been compiled. But your code must still #include Apple’s .h files so as to be able to see
Apple’s declarations. If you look at an iOS Xcode project, you’ll find that any .h files it
contains by default, as well as its main.m file, contain a line of this form:
#import <UIKit/UIKit.h>
That line is essentially a single massive #include that copies into your program the
declarations for the entire basic iOS API. Moreover, each of your .m files #imports its
corresponding .h file, including whatever the .h file #imports. Thus, all your code files
include the basic iOS declarations.
For example, earlier I said that CGPoint was defined like this:
struct CGPoint {
CGFloat x;
CGFloat y;
};
typedef struct CGPoint CGPoint;
After the preprocessor operates on all your files, your .m files actually contain that
definition of CGPoint. (In Xcode 3.2.x, you can even choose Build → Preprocess to
confirm that this is true.) And that is why your code is able to use a CGPoint!
The #import preprocessor directive is not mentioned in K&R. It’s an Objective-C ad-
dition to the language. It’s based on #include, but it is used instead of #include because
it (#import) contains some logic for making sure that the same material is not included
more than once. Such repeated inclusion is a danger whenever there are many cross-
dependent header files; use of #import solves the problem neatly.
The #import directive, like the #include directive (K&R 4.11), can specify a file in angle
brackets or in quotation marks:
#import <UIKit/UIKit.h>
#import "MyHeader.h"
The quotation marks form means “look for the named file in the same folder as this
file” (the .m file in which the #import line occurs). The angle brackets form means to
look among the various header search paths supplied in the build settings; these search
paths are set for you automatically, and you normally won’t need to modify them. In
general, the distinction means that you’ll use angle brackets to refer to a header file
owned by the Cocoa API and quotation marks to refer to a header file that you wrote.
If you’re curious as to what an #import directive imports, select it (in Xcode) and choose
File → Open Quickly to display the contents of the designated header file.
26 | Chapter 1: Just Enough C
The Standard Library
You also have at your disposal a large collection of built-in C library files. A library file
is a centrally located collection of C functions, along with a .h file that you can include
in order to make those functions available to your code.
For example, suppose you want to round a float up to the next highest integer. The
way to do this is to call some variety of the ceil function. You can read the ceil man
page in Xcode, or by typing man ceil in the Terminal. The documentation tells you
what #include to use to incorporate the correct header and also shows you the function
declarations and tells you what those functions do. A small pure C program might thus
look like this:
#include <math.h>
float f = 4.5;
int i = ceilf(f); // now i is 5
In your iOS programs, math.h is included for you as part of the massive UIKit
#import, so there’s no need to include it again. But some library functions might require
an explicit #import.
The standard library is discussed in K&R Appendix B. But the modern standard library
has evolved since K&R; it is a superset of K&R’s library. Theceil function, for example,
is listed in K&R appendix B, but the ceilf function is not. Similarly, if you wanted to
generate a random number (which is likely if you’re writing a game program that needs
to incorporate some unpredictable behavior), you probably wouldn’t use the rand
function listed in K&R; you’d use the random function, which supersedes it.
Forgetting that Objective-C is C and that the C library functions are available to your
code is a common beginner mistake.
More Preprocessor Directives
Of the many other available preprocessor directives, the one you’ll use most often is
#define. It is followed by a name and a value; at preprocess time, the value is substituted
for the name down through this code file. As K&R very well explain (K&R 1.4), this is
a good way to prevent “magic numbers” from being hidden and hard-coded into your
program in a way that makes the program difficult to understand and maintain.
For example, in an iOS app that lays out some text fields vertically, I might want them
all to have the same space between them. Let’s say this space is 3.0. I shouldn’t write
3.0 repeatedly throughout my code as I calculate the layout; instead, I write:
#define MIDSPACE 3.0
Now instead of the “magic number” 3.0, my code uses a meaningful name, MIDSPACE;
at preprocessor time, the text MIDSPACE is replaced with the text 3.0. So it amounts to
More Preprocessor Directives | 27
the same thing, but if I decide to change this value and try a different one, all I have to
do change is the #define line, not every occurrence of the number 3.0.
A #define simply performs text substitution, so any expression can be used as the value.
Sometimes you’ll want that expression to be an NSString literal. In Cocoa, NSString
literals can be used as a key to a dictionary or the name of a notification. (Never mind
for now what a dictionary or a notification is.) This situation is an invitation to error.
If you have a dictionary containing a key @"mykey" and you mistype this elsewhere in
your code as @"myKey" or @"mikey", the compiler won’t complain, but your program
will misbehave. The solution is to define a name for this literal string:
#define MYKEY @"mykey"
Now use MYKEY throughout your code instead of @"mykey", and if you mistype MYKEY the
preprocess substitution won’t be performed and the compiler will complain, catching
the mistake for you.
The #define directive can also be used to create a macro (K&R 4.11.2), a more elaborate
form of text substitution. You’ll encounter a few Cocoa macros in the course of this
book, but they will appear indistinguishable from functions; their secret identity as
macros won’t concern you.
There is also a #pragma mark directive that’s useful with Xcode; I talk about it when
discussing the Xcode programming environment (Chapter 9).
Data Type Qualifiers
A variable’s data type can be declared with a qualifier before the name of the type,
modifying something about how that variable is to be used. For example, the declara-
tion can be preceded by the term const, which means (K&R 2.4) that it is illegal to
change the variable’s value; the variable must be initialized in the same line as the
declaration, and that’s the only value it can ever have.
You can use a const variable as an alternative way (instead of #define) to prevent “magic
numbers” and similar expressions. For example:
const NSString* MYKEY = @"Howdy";
The Cocoa API itself makes heavy use of this device. For example, in some circum-
stances Cocoa will pass a dictionary of information to your code. The documentation
tells you what keys this dictionary contains. But instead of telling you a key as a string,
the documentation tells you the key as a const NSString variable name:
UIKIT_EXTERN NSString *const UIApplicationStatusBarOrientationUserInfoKey;
(Never mind what UIKIT_EXTERN means.) This declaration tells you that UIApplication-
StatusBarOrientationUserInfoKey is the name of an NSString, and you are to trust that
its value is set for you. You are to go ahead and use this name whenever you want to
speak of this particular key, secure in the knowledge that the actual key name string
28 | Chapter 1: Just Enough C
will be substituted. You do not have to know what that actual key name string is. In
this way, if you make a mistake in typing the variable name, the compiler will catch the
mistake because you’ll be using the name of an undefined variable.
Another commonly used qualifier is static. This term is unfortunately used in two
rather different ways in C; the way I commonly use it is inside a function. Inside a
function, static indicates that the memory set aside for a variable should not be re-
leased after the function returns; rather, the variable remains and maintains its value
for the next time the function is called. A static variable is useful, for example, when
you want to call a function many times without the overhead of calculating the result
each time (after the first time). First test to see whether the static value has already been
calculated: if it hasn’t, this must be the first time the function is being called, so you
calculate it; if it has, you just return it. Here’s a schematic version:
int myfunction() {
static int result = 0; // 0 means we haven't done the calculation yet
if (result == 0) {
// calculate result and set it
}
return result;
}
A very common use of a static variable in Objective-C is to implement a singleton
instance returned by a class factory method. If that sounds complicated, don’t worry;
it isn’t. Here’s an example from my own code, which you can grasp even though we
haven’t discussed Objective-C yet:
+ (CardPainter*) sharedPainter {
static CardPainter* sp = nil;
if (nil == sp)
sp = [[CardPainter alloc] init];
return sp;
}
That code says: If the CardPainter instance sp has never been created, create it, and in
any case, now return it. Thus, no matter how many times this method is called, the
instance will be created just once and that same instance will be returned every time.
Data Type Qualifiers | 29
CHAPTER 2
Object-Based Programming
My object all sublime.
—W. S. Gilbert, The Mikado
Objective-C, the native language for programming the Cocoa API, is an object-oriented
language; in order to use it, the programmer must have an appreciation of the nature
of objects and object-based programming. There’s little point in learning the syntax of
Objective-C message sending or instantiation without a clear understanding of what a
message or an instance is. That is what this chapter is about.
Objects
An object, in programming, is based on the concept of an object in the real world. It’s
an independent, self-contained thing. These objects, unlike purely inert objects in the
real world, have abilities. So an object in programming is more like a clock than a rock;
it doesn’t just sit there, but actually does something. Perhaps one could compare an
object in programming more to the animate objects of the real world, as opposed to
the inanimate objects, except that — unlike real-world animate things — a program-
ming object is supposed to be predictable: in particular, it does what you tell it. In the
real world, you tell a dog to sit and anything can happen; in the programming world,
you tell a dog to sit and it sits. (This is why so many of us prefer programming to dealing
with the real world.)
In object-based programming, a program is organized into many discrete objects. This
organization can make life much easier for the programmer. Each object has abilities
that are specialized for that object. You can think of this as being a little like how an
automobile assembly line works. Each worker or station along the line does one thing
(screw on the bumpers, or paint the door, or whatever) and does it well. You can see
immediately how this organization helps the programmer. If the car is coming off the
assembly line with the door badly painted, it is very likely that the blame lies with the
door-painting object, so we know where to look for the bug in our code. Or, if we decide
31
Exploring the Variety of Random
Documents with Different Content
Fig. 94.
§ 13. Fig. 94, page 171, will serve to show the mode in which similar
arrangements are carried into the smallest detail. It is magnified four
times from a cluster of leaves in the foreground of the “Isis” (Liber
Studiorum). Figs. 95 and 96, page 172, show the arrangement of the two
groups composing it; the lower is purely symmetrical, with trefoiled
centre and broad masses for wings; the uppermost is a sweeping
continuous curve, symmetrical, but foreshortened. Both are clasped by
arrow-shaped leaves. The two whole groups themselves are, in turn,
members of another larger group, composing the entire foreground, and
consisting of broad dock-leaves, with minor clusters on the right and left,
of which these form the chief portion on the right side.
Fig. 95.
Fig. 96.
§ 14. Unless every leaf, and every visible point or object, however
small, forms a part of some harmony of this kind (these symmetrical
conditions being only the most simple and obvious), it has no business in
the picture. It is the necessary connection of all the forms and colors,
down to the last touch, which constitutes great or inventive work,
separated from all common work by an impassable gulf.
By diligently copying the etchings of the Liber Studiorum, the reader
may, however, easily attain the perception of the existence of these
relations, and be prepared to understand Turner’s more elaborate
composition. It would take many figures to disentangle and explain the
arrangements merely of the leaf cluster, Fig. 78, facing page 97; but that
there is a system, and that every leaf has a fixed value and place in it,
can hardly but be felt at a glance.
It is curious that, in spite of all the constant talkings of “composition”
which goes on among art students, true composition is just the last thing
which appears to be perceived. One would have thought that in this
group, at least, the value of the central black leaf would have been seen,
of which the principal function is to point towards, and continue, the line
of bank above. See Plate 62. But a glance at the published Plate in the
England series will show that no idea of the composition had occurred to
the engraver’s mind. He thought any leaves would do, and supplied them
from his own repertory of hack vegetation.
§ 15. I would willingly enlarge farther on this subject—it is a favorite
one with me; but the figures required for any exhaustive treatment of it
would form a separate volume. All that I can do is to indicate, as these
examples do sufficiently, the vast field open to the student’s analysis if he
cares to pursue the subject; and to mark for the general reader these two
strong conclusions:—that nothing in great work is ever either fortuitous or
contentious.
It is not fortuitous; that is to say, not left to fortune. The “must do it by
a kind of felicity” of Bacon is true; it is true also that an accident is often
suggestive to an inventor. Turner himself said, “I never lose an accident.”
But it is this not losing it, this taking things out of the hands of Fortune,
and putting them into those of force and foresight, which attest the
master. Chance may sometimes help, and sometimes provoke, a success;
but must never rule, and rarely allure.
And, lastly, nothing must be contentious. Art has many uses and many
pleasantnesses; but of all its services, none are higher than its setting
forth, by a visible and enduring image, the nature of all true authority
and freedom; Authority which defines and directs the action of
benevolent law; and Freedom which consists in deep and soft consent of
individual4 helpfulness.
1 The sails in the engraving were put in to catch the public eye. There are
none in the drawing.
2 These etchings of compositions are all reversed, for they are merely
sketches on the steel, and I cannot sketch easily except straight from the
drawing, and without reversing. The looking-glass plagues me with cross lights.
As examples of composition, it does not the least matter which way they are
turned; and the reader may see this Schaffhausen subject from the right side
of the Rhine, by holding the book before a glass. The rude indications of the
figures in the Loire subject are nearly facsimiles of Turner’s.
3 With the exception of the jagged ledge rising out of the foam below which
comes from the north side, and is admirable in its expression of the position of
the limestone-beds, which, rising from below the drift gravel of Constance, are
the real cause of the fall of Schaffhausen.
4 “Individual,” that is to say, distinct and separate in character, though
joined in purpose. I might have enlarged on this head, but that all I should
care to say has been already said admirably by Mr. J. S. Mill in his essay on
Liberty.
CHAPTER III.
THE RULE OF THE GREATEST.
§ 1. In the entire range of art principles, none perhaps present a
difficulty so great to the student, or require from the teacher expression
so cautious, and yet so strong, as those which concern the nature and
influence of magnitude.
In one sense, and that deep, there is no such thing as magnitude. The
least thing is as the greatest, and one day as a thousand years, in the
eyes of the Maker of great and small things. In another sense, and that
close to us and necessary, there exist both magnitude and value. Though
not a sparrow falls to the ground unnoted, there are yet creatures who
are of more value than many; and the same Spirit which weighs the dust
of the earth in a balance, counts the isles as a little thing.
§ 2. The just temper of human mind in this matter may, nevertheless,
be told shortly. Greatness can only be rightly estimated when minuteness
is justly reverenced. Greatness is the aggregation of minuteness; nor can
its sublimity be felt truthfully by any mind unaccustomed to the
affectionate watching of what is least.
But if this affection for the least be unaccompanied by the powers of
comparison and reflection; if it be intemperate in its thirst, restless in
curiosity, and incapable of the patient and self-commandant pause which
is wise to arrange, and submissive to refuse, it will close the paths of
noble art to the student as effectually, and hopelessly, as even the
blindness of pride, or impatience of ambition.
§ 3. I say the paths of noble art, not of useful art. All accurate
investigation will have its reward; the morbid curiosity will at least slake
the thirst of others, if not its own; and the diffused and petty affections
will distribute, in serviceable measure, their minute delights and narrow
discoveries. The opposite error, the desire of greatness as such, or rather
of what appears great to indolence and vanity;—the instinct which I have
described in the “Seven Lamps,” noting it, among the Renaissance
builders, to be an especial and unfailing sign of baseness of mind, is as
fruitless as it is vile; no way profitable—every way harmful: the widest
and most corrupting expression of vulgarity. The microscopic drawing of
an insect may be precious; but nothing except disgrace and misguidance
will ever be gathered from such work as that of Haydon or Barry.
§ 4. The work I have mostly had to do, since this essay was begun, has
been that of contention against such debased issues of swollen insolence
and windy conceit; but I have noticed lately, that some lightly-budding
philosophers have depreciated true greatness; confusing the relations of
scale, as they bear upon human instinct and morality; reasoning as if a
mountain were no nobler than a grain of sand, or as if many souls were
not of mightier interest than one. To whom it must be shortly answered
that the Lord of power and life knew which were His noblest works, when
He bade His servant watch the play of the Leviathan, rather than dissect
the spawn of the minnow; and that when it comes to practical question
whether a single soul is to be jeoparded for many, and this Leonidas, or
Curtius, or Winkelried shall abolish—so far as abolishable—his own spirit,
that he may save more numerous spirits, such question is to be solved by
the simple human instinct respecting number and magnitude, not by
reasonings on infinity:—
“Le navigateur, qui, la nuit, voit l’océan étinceler de lumière,
danser en guirlandes de feu, s’égaye d’abord de ce spectacle. Il fait
dix lieues; la guirlande s’allonge indéfiniment, elle s’agite, se tord, se
noue, aux mouvements de la lame; c’est un serpent monstrueux qui
va toujours s’allongeant, jusqu’à trente lieues, quarante lieues. Et
tout cela n’est qu’une danse d’animalcules imperceptibles. En quel
nombre? A cette question l’imagination s’effraye; elle sent là une
nature de puissance immense, de richesse epouvantable.... Que sont
ces petits des petits? Rien moins que les constructeurs du globe où
nous sommes. De leurs corps, de leurs débris, ils ont préparé le sol
qui est sous nos pas.... Et ce sont les plus petits qui ont fait les plus
grandes choses. L’imperceptible rhizopode s’est bâti un monument
bien autre que les pyramides, pas moins que l’Italie centrale, une
notable partie de la chaîne des Apennins. Mais c’était trop peu
encore; les masses énormes du Chili, les prodigieuses Cordillères, qui
regardent le monde à leurs pieds, sont le monument funéraire où cet
être insaisissable, et pour ainsi dire, invisible, a enseveli les débris de
son espèce dïsparue.”—(Michelet: L’Insecte.)
§ 5. In these passages, and those connected with them in the chapter
from which they are taken, itself so vast in scope, and therefore so
sublime, we may perhaps find the true relations of minuteness,
multitude, and magnitude. We shall not feel that there is no such thing as
littleness, or no such thing as magnitude. Nor shall we be disposed to
confuse a Volvox with the Cordilleras; but we may learn that they both
are bound together by links of eternal life and toil; we shall see the
vastest thing noble, chiefly for what it includes; and the meanest for what
it accomplishes. Thence we might gather—and the conclusion will be
found in experience true—that the sense of largeness would be most
grateful to minds capable of comprehending, balancing, and comparing;
but capable also of great patience and expectation; while the sense of
minute wonderfulness would be attractive to minds acted upon by sharp,
small, penetrative sympathies, and apt to be impatient, irregular, and
partial. This fact is curiously shown in the relations between the temper
of the great composers and the modern pathetic school. I was surprised
at the first rise of that school, now some years ago, by observing how
they restrained themselves to subjects which in other hands would have
been wholly uninteresting (compare Vol. IV., p. 19); and in their
succeeding efforts, I saw with increasing wonder, that they were almost
destitute of the power of feeling vastness, or enjoying the forms which
expressed it. A mountain or great building only appeared to them as a
piece of color of a certain shape. The powers it represented, or included,
were invisible to them. In general they avoided subjects expressing space
or mass, and fastened on confined, broken, and sharp forms; liking furze,
fern, reeds, straw, stubble, dead leaves, and such like, better than strong
stones, broad-flowing leaves, or rounded hills: in all such greater things,
when forced to paint them, they missed the main and mighty lines; and
this no less in what they loved than in what they disliked; for though fond
of foliage, their trees always had a tendency to congeal into little acicular
thorn-hedges, and never tossed free. Which modes of choice proceed
naturally from a petulant sympathy with local and immediately visible
interests or sorrows, not regarding their large consequences, nor capable
of understanding more massive view or more deeply deliberate
mercifulness;—but peevish and horror-struck, and often incapable of self-
control, though not of self-sacrifice. There are more people who can
forget themselves than govern themselves.
This narrowly pungent and bitter virtue has, however, its beautiful
uses, and is of special value in the present day, when surface-work,
shallow generalization, and cold arithmetical estimates of things, are
among the chief dangers and causes of misery which men have to deal
with.
§ 6. On the other hand, and in clear distinction from all such workers, it
is to be remembered that the great composers, not less deep in feeling,
are in the fixed habit of regarding as much the relations and positions, as
the separate nature, of things; that they reap and thrash in the sheaf,
never pluck ears to rub in the hand; fish with net, not line, and sweep
their prey together within great cords of errorless curve;—that nothing
ever bears to them a separate or isolated aspect, but leads or links a
chain of aspects—that to them it is not merely the surface, nor the
substance, of anything that is of import; but its circumference and
continence: that they are pre-eminently patient and reserved; observant,
not curious;—comprehensive, not conjectural; calm exceedingly;
unerring, constant, terrible in steadfastness of intent; unconquerable:
incomprehensible: always suggesting, implying, including, more than can
be told.
§ 7. And this may be seen down to their treatment of the smallest
things.
For there is nothing so small but we may, as we choose, see it in the
whole, or in part, and in subdued connection with other things, or in
individual and petty prominence. The greatest treatment is always that
which gives conception the widest range, and most harmonious
guidance;—it being permitted us to employ a certain quantity of time,
and certain number of touches of pencil—he who with these embraces
the largest sphere of thought, and suggests within that sphere the most
perfect order of thought, has wrought the most wisely, and therefore
most nobly.
§ 8. I do not, however, purpose here to examine or illustrate the nature
of great treatment—to do so effectually would need many examples from
the figure composers; and it will be better (if I have time to work out the
subject carefully) that I should do so in a form which may be easily
accessible to young students. Here I will only state in conclusion what it
is chiefly important for all students to be convinced of, that all the
technical qualities by which greatness of treatment is known, such as
reserve in color, tranquillity and largeness of line, and refusal of
unnecessary objects of interest, are, when they are real, the exponents
of an habitually noble temper of mind, never the observances of a
precept supposed to be useful. The refusal or reserve of a mighty painter
cannot be imitated; it is only by reaching the same intellectual strength
that you will be able to give an equal dignity to your self-denial. No one
can tell you beforehand what to accept, or what to ignore; only
remember always, in painting as in eloquence, the greater your strength,
the quieter will be your manner, and the fewer your words; and in
painting, as in all the arts and acts of life, the secret of high success will
be found, not in a fretful, and various excellence, but in a quiet
singleness of justly chosen aim.
CHAPTER IV.
THE LAW OF PERFECTNESS.
§1. Among the several characteristics of great treatment which in
the last chapter were alluded to without being enlarged upon, one will be
found several times named;—reserve.
It is necessary for our present purpose that we should understand this
quality more distinctly. I mean by it the power which a great painter
exercises over himself in fixing certain limits, either of force, of color, or
of quantity of work;—limits which he will not transgress in any part of his
picture, even though here and there a painful sense of incompletion may
exist, under the fixed conditions, and might tempt an inferior workman to
infringe them. The nature of this reserve we must understand in order
that we may also determine the nature of true completion or perfectness,
which is the end of composition.
§ 2. For perfectness, properly so called, means harmony. The word
signifies, literally, the doing our work thoroughly. It does not mean
carrying it up to any constant and established degree of finish, but
carrying the whole of it up to a degree determined upon. In a chalk or
pencil sketch by a great master, it will often be found that the deepest
shades are feeble tints of pale gray; the outlines nearly invisible, and the
forms brought out by a ghostly delicacy of touch, which, on looking close
to the paper, will be indistinguishable from its general texture. A single
line of ink, occurring anywhere in such a drawing, would of course
destroy it; placed in the darkness of a mouth or nostril, it would turn the
expression into a caricature; on a cheek or brow it would be simply a
blot. Yet let the blot remain, and let the master work up to it with lines of
similar force; and the drawing which was before perfect, in terms of
pencil, will become, under his hand, perfect in terms of ink; and what
was before a scratch on the cheek will become a necessary and beautiful
part of its gradation.
All great work is thus reduced under certain conditions, and its right to
be called complete depends on its fulfilment of them, not on the nature
of the conditions chosen. Habitually, indeed, we call a colored work which
is satisfactory to us, finished, and a chalk drawing unfinished; but in the
mind of the master, all his work is, according to the sense in which you
use the word, equally perfect or imperfect. Perfect, if you regard its
purpose and limitation; imperfect, if you compare it with the natural
standard. In what appears to you consummate, the master has assigned
to himself terms of shortcoming, and marked with a sad severity the
point up to which he will permit himself to contend with nature. Were it
not for his acceptance of such restraint, he could neither quit his work,
nor endure it. He could not quit it, for he would always perceive more
that might be done; he could not endure it, because all doing ended only
in more elaborate deficiency.
§ 3. But we are apt to forget, in modern days, that the reserve of a
man who is not putting forth half his strength is different in manner and
dignity from the effort of one who can do no more. Charmed, and justly
charmed, by the harmonious sketches of great painters, and by the
grandeur of their acquiescence in the point of pause, we have put
ourselves to produce sketches as an end instead of a means, and thought
to imitate the painter’s scornful restraint of his own power, by a scornful
rejection of the things beyond ours. For many reasons, therefore, it
becomes desirable to understand precisely and finally what a good
painter means by completion.
§ 4. The sketches of true painters may be classed under the following
heads:—
I. Experimental.—In which they are assisting an imperfect conception
of a subject by trying the look of it on paper in different ways.
By the greatest men this kind of sketch is hardly ever made; they
conceive their subjects distinctly at once, and their sketch is not to try
them, but to fasten them down. Raphael’s form the only important
exception—and the numerous examples of experimental work by him are
evidence of his composition being technical rather than imaginative. I
have never seen a drawing of the kind by any great Venetian. Among the
nineteen thousand sketches by Turner—which I arranged in the National
Gallery—there was, to the best of my recollection, not one. In several
instances the work, after being carried forward a certain length, had been
abandoned and begun again with another view; sometimes also two or
more modes of treatment had been set side by side with a view to
choice. But there were always two distinct imaginations contending for
realization—not experimental modifications of one.
§ 5. II. Determinant.—The fastening down of an idea in the simplest
terms, in order that it may not be disturbed or confused by after work.
Nearly all the great composers do this, methodically, before beginning a
painting. Such sketches are usually in a high degree resolute and
compressive; the best of them outlined or marked calmly with the pen,
and deliberately washed with color, indicating the places of the principal
lights.
Fine drawings of this class never show any hurry or confusion. They
are the expression of concluded operations of mind, are drawn slowly,
and are not so much sketches, as maps.
§ 6. III. Commemorative.—Containing records of facts which the
master required. These in their most elaborate form are “studies,” or
drawings, from Nature, of parts needed in the composition, often highly
finished in the part which is to be introduced. In this form, however, they
never occur by the greatest imaginative masters. For by a truly great
inventor everything is invented; no atom of the work is unmodified by his
mind; and no study from nature, however beautiful, could be introduced
by him into his design without change; it would not fit with the rest.
Finished studies for introduction are therefore chiefly by Leonardo and
Raphael, both technical designers rather than imaginative ones.
Commemorative sketches, by great masters, are generally hasty,
merely to put them in mind of motives of invention, or they are
shorthand memoranda of things with which they do not care to trouble
their memory; or, finally, accurate notes of things which they must not
modify by invention, as local detail, costume, and such like. You may find
perfectly accurate drawings of coats of arms, portions of dresses, pieces
of architecture, and so on, by all the great men; but you will not find
elaborate studies of bits of their pictures.
Fig. 97.
§ 7. When the sketch is made merely as a memorandum, it is
impossible to say how little, or what kind of drawing, may be sufficient
for the purpose. It is of course likely to be hasty from its very nature, and
unless the exact purpose be understood, it may be as unintelligible as a
piece of shorthand writing. For instance, in the corner of a sheet of
sketches made at sea, among those of Turner, at the National Gallery,
occurs this one, Fig. 97. I suppose most persons would not see much use
in it. It nevertheless was probably one of the most important sketches
made in Turner’s life, fixing for ever in his mind certain facts respecting
the sunrise from a clear sea-horizon. Having myself watched such
sunrise, occasionally, I perceive this sketch to mean as follows:—
(Half circle at the top.) When the sun was only half out of the sea, the
horizon was sharply traced across its disk, and red streaks of vapor
crossed the lower part of it.
(Horseshoe underneath.) When the sun had risen so far as to show
three-quarters of its diameter, its light became so great as to conceal the
sea-horizon, consuming it away in descending rays.
(Smaller horseshoe below.) When on the point of detaching itself from
the horizon, the sun still consumed away the line of the sea, and looked
as if pulled down by it.
(Broken oval.) Having risen about a fourth of its diameter above the
horizon, the sea-line reappeared; but the risen orb was flattened by
refraction into an oval.
(Broken circle.) Having risen a little farther above the sea-line, the sun,
at last, got itself round, and all right, with sparkling reflection on the
waves just below the sea-line.
This memorandum is for its purpose entirely perfect and efficient,
though the sun is not drawn carefully round, but with a dash of the
pencil; but there is no affected or desired slightness. Could it have been
drawn round as instantaneously, it would have been. The purpose is
throughout determined; there is no scrawling, as in vulgar sketching.1
§ 8. Again, Fig. 98 is a facsimile of one of Turner’s “memoranda,” of a
complete subject,2 Lausanne, from the road to Fribourg.
To face page
Fig. 98.
This example is entirely characteristic of his usual drawings from
nature, which unite two characters, being both commemorative and
determinant:—Commemorative, in so far as they note certain facts about
the place: determinant, in that they record an impression received from
the place there and then, together with the principal arrangement of the
composition in which it was afterwards to be recorded. In this mode of
sketching, Turner differs from all other men whose work I have studied.
He never draws accurately on the spot, with the intention of modifying or
composing afterwards from the materials; but instantly modifies as he
draws, placing his memoranda where they are to be ultimately used, and
taking exactly what he wants, not a fragment or line more.
§ 9. This sketch has been made in the afternoon. He had been
impressed as he walked up the hill, by the vanishing of the lake in the
golden horizon, without end of waters, and by the opposition of the
pinnacled castle and cathedral to its level breadth. That must be drawn!
and from this spot, where all the buildings are set well together. But it
lucklessly happens that, though the buildings come just where he wants
them in situation, they don’t in height. For the castle (the square mass on
the right) is in reality higher than the cathedral, and would block out the
end of the lake. Down it goes instantly a hundred feet, that we may see
the lake over it; without the smallest regard for the military position of
Lausanne.
§ 10. Next: The last low spire on the left is in truth concealed behind
the nearer bank, the town running far down the hill (and climbing
another hill) in that direction. But the group oi spires, without it, would
not be rich enough to give a proper impression of Lausanne, as a spiry
place. Turner quietly sends to fetch the church from round the corner,
places it where he likes, and indicates its distance only by aërial
perspective (much greater in the pencil drawing than in the woodcut).
§ 11. But again: Not only the spire of the lower church, but the peak of
the Rochers d’Enfer (that highest in the distance) would in reality be out
of sight; it is much farther round to the left. This would never do either;
for without it, we should have no idea that Lausanne was opposite the
mountains, nor should we have a nice sloping line to lead us into the
distance.
With the same unblushing tranquillity of mind in which he had ordered
up the church, Turner sends also to fetch the Rochers d’Enfer; and puts
them also where he chooses, to crown the slope of distant hill, which, as
every traveller knows, in its decline to the west, is one of the most
notable features of the view from Lausanne.
§ 12. These modifications, easily traceable in the large features of the
design, are carried out with equal audacity and precision in every part of
it. Every one of those confused lines on the right indicates something that
is really there, only everything is shifted and sorted into the exact places
that Turner chose. The group of dark objects near us at the foot of the
bank is a cluster of mills, which, when the picture was completed, were
to be the blackest things in it, and to throw back the castle, and the
golden horizon; while the rounded touches at the bottom, under the
castle, indicate a row of trees, which follow a brook coming out of the
ravine behind us; and were going to be made very round indeed in the
picture (to oppose the spiky and angular masses of castle) and very
consecutive, in order to form another conducting line into the distance.
§ 13. These motives, or motives like them, might perhaps be guessed
on looking at the sketch. But no one without going to the spot would
understand the meaning of the vertical lines in the left-hand lowest
corner.
They are a “memorandum” of the artificial verticalness of a low
sandstone cliff, which has been cut down there to give space for a bit of
garden belonging to a public-house beneath, from which garden a path
leads along the ravine to the Lausanne rifle ground. The value of these
vertical lines in repeating those of the cathedral is very great; it would be
greater still in the completed picture, increasing the sense of looking
down from a height, and giving grasp of, and power over, the whole
scene.
§ 14. Throughout the sketch, as in all that Turner made, the observing
and combining intellect acts in the same manner. Not a line is lost, nor a
moment of time; and though the pencil flies, and the whole thing is
literally done as fast as a piece of shorthand writing, it is to the full as
purposeful and compressed, so that while there are indeed dashes of the
pencil which are unintentional, they are only unintentional as the form of
a letter is, in fast writing, not from want of intention, but from the
accident of haste.
§ 15. I know not if the reader can understand,—I myself cannot,
though I see it to be demonstrable,—the simultaneous occurrence of idea
which produces such a drawing as this: the grasp of the whole, from the
laying of the first line, which induces continual modifications of all that is
done, out of respect to parts not done yet. No line is ever changed or
effaced: no experiment made; but every touch is placed with reference to
all that are to succeed, as to all that have gone before; every addition
takes its part, as the stones in an arch of a bridge; the last touch locks
the arch. Remove that keystone, or remove any other of the stones of the
vault, and the whole will fall.
§ 16. I repeat—the power of mind which accomplishes this, is yet
wholly inexplicable to me, as it was when first I defined it in the chapter
on imagination associative, in the second volume. But the grandeur of the
power impresses me daily more and more; and, in quitting the subject of
invention, let me assert finally, in clearest and strongest terms, that no
painting is of any true imaginative perfectness at all, unless it has been
thus conceived.
One sign of its being thus conceived may be always found in the
straightforwardness of its work. There are continual disputes among
artists as to the best way of doing things, which may nearly all be
resolved into confessions of indetermination. If you know precisely what
you want, you will not feel much hesitation in setting about it; and a
picture may be painted almost any way, so only that it can be a straight
way. Give a true painter a ground of black, white, scarlet, or green, and
out of it he will bring what you choose. From the black, brightness; from
the white, sadness; from the scarlet, coolness; from the green, glow: he
will make anything out of anything, but in each case his method will be
pure, direct, perfect, the shortest and simplest possible. You will find him,
moreover, indifferent as to succession of process. Ask him to begin at the
bottom of the picture instead of the top,—to finish two square inches of it
without touching the rest, or to lay a separate ground for every part
before finishing any;—it is all the same to him! What he will do if left to
himself, depends on mechanical convenience, and on the time at his
disposal. If he has a large brush in his hand, and plenty of one color
ground, he may lay as much as is wanted of that color, at once, in every
part of the picture where it is to occur; and if any is left, perhaps walk to
another canvas, and lay the rest of it where it will be wanted on that. If,
on the contrary, he has a small brush in his hand, and is interested in a
particular spot of the picture, he will, perhaps, not stir from it till that bit
is finished. But the absolutely best, or centrally, and entirely right way of
painting is as follows:—
§ 17. A light ground, white, red, yellow, or gray, not brown, or black.
On that an entirely accurate, and firm black outline of the whole picture,
in its principal masses. The outline to be exquisitely correct as far as it
reaches, but not to include small details; the use of it being to limit the
masses of first color. The ground-colors then to be laid firmly, each on its
own proper part of the picture, as inlaid work in a mosaic table, meeting
each other truly at the edges: as much of each being laid as will get itself
into the state which the artist requires it to be in for his second painting,
by the time he comes to it. On this first color, the second colors and
subordinate masses laid in due order, now, of course, necessarily without
previous outline, and all small detail reserved to the last, the bracelet
being not touched, nor indicated in the last, till the arm is finished.3
§ 18. This is, as far as it can be expressed in few words, the right, or
Venetian way of painting; but it is incapable of absolute definition, for it
depends on the scale, the material, and the nature of the object
represented, how much a great painter will do with his first color; or how
many after processes he will use. Very often the first color, richly blended
and worked into, is also the last; sometimes it wants a glaze only to
modify it; sometimes an entirely different color above it. Turner’s storm-
blues, for instance, were produced by a black ground, with opaque blue,
mixed with white, struck over it.4 The amount of detail given in the first
color will also depend on convenience. For instance, if a jewel fastens a
fold of dress, a Venetian will lay probably a piece of the jewel color in its
place at the time he draws the fold; but if the jewel falls upon the dress,
he will paint the folds only in the ground color, and the jewel afterwards.
For in the first case his hand must pause, at any rate, where the fold is
fastened; so that he may as well mark the color of the gem: but he would
have to check his hand in the sweep with which he drew the drapery, if
he painted a jewel that fell upon it with the first color. So far, however, as
he can possibly use the under color, he will, in whatever he has to
superimpose. There is a pretty little instance of such economical work in
the painting of the pearls on the breast of the elder princess, in our best
Paul Veronese (Family of Darius). The lowest is about the size of a small
hazel-nut, and falls on her rose-red dress. Any other but a Venetian
would have put a complete piece of white paint over the dress, for the
whole pearl, and painted into that the colors of the stone. But Veronese
knows beforehand that all the dark side of the pearl will reflect the red of
the dress. He will not put white over the red, only to put red over the
white again. He leaves the actual dress for the dark side of the pearl, and
with two small separate touches, one white, another brown, places its
high light and shadow. This he does with perfect care and calm; but in
two decisive seconds. There is no dash, nor display, nor hurry, nor error.
The exactly right thing is done in the exactly right place, and not one
atom of color, nor moment of time spent vainly. Look close at the two
touches,—you wonder what they mean. Retire six feet from the picture—
the pearl is there!
§ 19. The degree in which the ground colors are extended over his
picture, as he works, is to a great painter absolutely indifferent. It is all
the same to him whether he grounds a head, and finishes it at once to
the shoulders, leaving all round it white; or whether he grounds the
whole picture. His harmony, paint as he will, never can be complete till
the last touch is given; so long as it remains incomplete, he does not care
how little of it is suggested, or how many notes are missing. All is wrong
till all is right; and he must be able to bear the all-wrongness till his work
is done, or he cannot paint at all. His mode of treatment will, therefore,
depend on the nature of his subject; as is beautifully shown in the water-
color sketches by Turner in the National Gallery. His general system was
to complete inch by inch; leaving the paper quite white all round,
especially if the work was to be delicate. The most exquisite drawings left
unfinished in the collection—those at Rome and Naples—are thus outlined
accurately on pure white paper, begun in the middle of the sheet, and
worked out to the side, finishing as he proceeds. If, however, any united
effect of light or color is to embrace a large part of the subject, he will lay
it in with a broad wash over the whole paper at once; then paint into it
using it as a ground, and modifying it in the pure Venetian manner. His oil
pictures were laid roughly with ground colors, and painted into with such
rapid skill, that the artists who used to see him finishing at the Academy
sometimes suspected him of having the picture finished underneath the
colors he showed, and removing, instead of adding, as they watched.
§ 20. But, whatever the means used may be, the certainty and
directness of them imply absolute grasp of the whole subject, and
without this grasp there is no good painting. This, finally, let me declare,
without qualification—that partial conception is no conception. The whole
picture must be imagined, or none of it is. And this grasp of the whole
implies very strange and sublime qualities of mind. It is not possible,
unless the feelings are completely under control; the least excitement or
passion will disturb the measured equity of power; a painter needs to be
as cool as a general; and as little moved or subdued by his sense of
pleasure, as a soldier by the sense of pain. Nothing good can be done
without intense feeling; but it must be feeling so crushed, that the work
is set about with mechanical steadiness, absolutely untroubled, as a
surgeon,—not without pity, but conquering it and putting it aside—begins
an operation. Until the feelings can give strength enough to the will to
enable it to conquer them, they are not strong enough. If you cannot
leave your picture at any moment;—cannot turn from it and go on with
another, while the color is drying;—cannot work at any part of it you
choose with equal contentment—you have not firm enough grasp of it.
§ 21. It follows also, that no vain or selfish person can possibly paint,
in the noble sense of the word. Vanity and selfishness are troublous,
eager, anxious, petulant:—painting can only be done in calm of mind.
Resolution is not enough to secure this; it must be secured by disposition
as well. You may resolve to think of your picture only; but, if you have
been fretted before beginning, no manly or clear grasp of it will be
possible for you. No forced calm is calm enough. Only honest calm,—
natural calm. You might as well try by external pressure to smoothe a
lake till it could reflect the sky, as by violence of effort to secure the
peace through which only you can reach imagination. That peace must
come in its own time; as the waters settle themselves into clearness as
well as quietness; you can no more filter your mind into purity than you
can compress it into calmness; you must keep it pure, if you would have
it pure; and throw no stones into it, if you would have it quiet. Great
courage and self-command may, to a certain extent, give power of
painting without the true calmness underneath; but never of doing first-
rate work. There is sufficient evidence of this, in even what we know of
great men, though of the greatest, we nearly always know the least (and
that necessarily; they being very silent, and not much given to setting
themselves forth to questioners; apt to be contemptuously reserved, no
less than unselfishly). But in such writings and sayings as we possess of
theirs, we may trace a quite curious gentleness and serene courtesy.
Rubens’ letters are almost ludicrous in their unhurried politeness.
Reynolds, swiftest of painters, was gentlest of companions; so also
Velasquez, Titian, and Veronese.
§ 22. It is gratuitous to add that no shallow or petty person can paint.
Mere cleverness or special gift never made an artist. It is only perfectness
of mind, unity, depth, decision, the highest qualities, in fine, of the
intellect, which will form the imagination.
§ 23. And, lastly, no false person can paint. A person false at heart
may, when it suits his purposes, seize a stray truth here or there; but the
relations of truth,—its perfectness,—that which makes it wholesome
truth, he can never perceive. As wholeness and wholesomeness go
together, so also sight with sincerity; it is only the constant desire of, and
submissiveness to truth, which can measure its strange angles and mark
its infinite aspects; and fit them and knit them into the strength of sacred
invention.
Sacred, I call it deliberately; for it is thus, in the most accurate senses,
humble as well as helpful; meek in its receiving, as magnificent in its
disposing; the name it bears being rightly given to invention formal, not
because it forms, but because it finds. For you cannot find a lie; you must
make it for yourself. False things may be imagined, and false things
composed; but only truth can be invented.
1 The word in the uppermost note, to the right of the sun, is “red;” the
others, “yellow,” “purple,” “cold” light gray. He always noted the colors of the
skies in this way.
2 It is not so good a facsimile as those I have given from Durer, for the
original sketch is in light pencil; and the thickening and delicate emphasis of
the lines, on which nearly all the beauty of the drawing depended, cannot be
expressed in the woodcut, though marked by a double line as well as I could.
But the figure will answer its purpose well enough in showing Turner’s mode of
sketching.
3 Thus, in the Holy Family of Titian, lately purchased for the National
Gallery, the piece of St. Catherine’s dress over her shoulders is painted on the
under dress, after that was dry. All its value would have been lost, had the
slightest tint or trace of it been given previously. This picture, I think, and
certainly many of Tintoret’s, are painted on dark grounds; but this is to save
time, and with some loss to the future brightness of the color.
4 In cleaning the “Hero and Leander,” now in the National collection, these
upper glazes were taken off, and only the black ground left. I remember the
picture when its distance was of the most exquisite blue. I have no doubt the
“Fire at Sea” has had its distance destroyed in the same manner.
PART IX.
OF IDEAS OF RELATION:—II. OF
INVENTION SPIRITUAL.
—————
CHAPTER I.
THE DARK MIRROR.
§ 1. In the course of our inquiry into the moral of landscape (Vol. III.,
chap. 17), we promised, at the close of our work, to seek for some better,
or at least clearer, conclusions than were then possible to us. We
confined ourselves in that chapter to the vindication of the probable
utility of the love of natural scenery. We made no assertion of the
usefulness of painting such scenery. It might be well to delight in the real
country, or admire the real flowers and true mountains. But it did not
follow that it was advisable to paint them.
Far from it. Many reasons might be given why we should not paint
them. All the purposes of good which we saw that the beauty of nature
could accomplish, may be better fulfilled by the meanest of her realities
than by the brightest of imitations. For prolonged entertainment, no
picture can be compared with the wealth of interest which may be found
in the herbage of the poorest field, or blossoms of the narrowest copse.
As suggestive of supernatural power, the passing away of a fitful rain-
cloud, or opening of dawn, are in their change and mystery more
pregnant than any pictures. A child would, I suppose, receive a religious
lesson from a flower more willingly than from a print of one, and might
be taught to understand the nineteenth Psalm, on a starry night, better
than by diagrams of the constellations.
Whence it might seem a waste of time to draw landscape at all.
I believe it is;—to draw landscape mere and solitary, however beautiful
(unless it be for the sake of geographical or other science, or of historical
record). But there is a kind of landscape which it is not inexpedient to
draw. What kind, we may probably discover by considering that which
mankind has hitherto contented itself with painting.
§ 2. We may arrange nearly all existing landscape under the following
heads:—
I. Heroic.—Representing an imaginary world, inhabited by men not
perhaps perfectly civilized, but noble, and usually subjected to severe
trials, and by spiritual powers of the highest order. It is frequently without
architecture; never without figure-action, or emotion. Its principal master
is Titian.
II. Classical.—Representing an imaginary world, inhabited by perfectly
civilized men, and by spiritual powers of an inferior order.
It generally assumes this condition of things to have existed among the
Greek and Roman nations. It contains usually architecture of an elevated
character, and always incidents of figure-action and emotion. Its principal
master is Nicolo Poussin.
III. Pastoral.—Representing peasant life and its daily work, or such
scenery as may naturally be suggestive of it, consisting usually of simple
landscape, in part subjected to agriculture, with figures, cattle, and
domestic buildings. No supernatural being is ever visibly present. It does
not in ordinary cases admit architecture of an elevated character, nor
exciting incident. Its principal master is Cuyp.
IV. Contemplative.—Directed principally to the observance of the powers
of Nature, and record of the historical associations connected with
landscape, illustrated by, or contrasted with, existing states of human life.
No supernatural being is visibly present. It admits every variety of
subject, and requires, in general, figure incident, but not of an exciting
character. It was not developed completely until recent times. Its principal
master is Turner.1
§ 3. These are the four true orders of landscape, not of course
distinctly separated from each other in all cases, but very distinctly in
typical examples. Two spurious forms require separate note.
(a.) Picturesque.—This is indeed rather the degradation (or sometimes
the undeveloped state) of the Contemplative, than a distinct class; but it
may be considered generally as including pictures meant to display the
skill of the artist, and his powers of composition; or to give agreeable
forms and colors, irrespective of sentiment. It will include much modern
art, with the street views and church interiors of the Dutch, and the
works of Canaletto, Guardi, Tempesta, and the like.
(b.) Hybrid.—Landscape in which the painter endeavors to unite the
irreconcileable sentiment of two or more of the above-named classes. Its
principal masters are Berghem and Wouvermans.
§ 4. Passing for the present by these inferior schools, we find that all
true landscape, whether simple or exalted, depends primarily for its
interest on connection with humanity, or with spiritual powers. Banish
your heroes and nymphs from the classical landscape—its laurel shades
will move you no more. Show that the dark clefts of the most romantic
mountain are uninhabited and untraversed; it will cease to be romantic.
Fields without shepherds and without fairies will have no gaiety in their
green, nor will the noblest masses of ground or colors of cloud arrest or
raise your thoughts, if the earth has no life to sustain, and the heaven
none to refresh.
§ 5. It might perhaps be thought that, since from scenes in which the
figure was principal, and landscape symbolical and subordinate (as in the
art of Egypt), the process of ages had led us to scenes in which
landscape was principal and the figure subordinate,—a continuance in the
same current of feeling might bring forth at last an art from which
humanity and its interests should wholly vanish, leaving us to the
passionless admiration of herbage and stone. But this will not, and
cannot be. For observe the parallel instance in the gradually increasing
importance of dress. From the simplicity of Greek design, concentrating, I
suppose, its skill chiefly on the naked form, the course of time developed
conditions of Venetian imagination which found nearly as much interest,
and expressed nearly as much dignity, in folds of dress and fancies of
decoration as in the faces of the figures themselves; so that if from
Veronese’s Marriage in Cana we remove the architecture and the gay
dresses, we shall not in the faces and hands remaining, find a satisfactory
abstract of the picture. But try it the other way. Take out the faces; leave
the draperies, and how then? Put the fine dresses and jewelled girdles
into the best group you can; paint them with all Veronese’s skill: will they
satisfy you?
§ 6. Not so. As long as they are in their due service and subjection—
while their folds are formed by the motion of men, and their lustre adorns
the nobleness of men—so long the lustre and the folds are lovely. But
cast them from the human limbs;—golden circlet and silken tissue are
withered; the dead leaves of autumn are more precious than they.
This is just as true, but in a far deeper sense, of the weaving of the
natural robe of man’s soul. Fragrant tissue of flowers, golden circlets of
clouds, are only fair when they meet the fondness of human thoughts,
and glorify human visions of heaven.
§ 7. It is the leaning on this truth which, more than any other, has been
the distinctive character of all my own past work. And in closing a series
of Art-studies, prolonged during so many years, it may be perhaps
permitted me to point out this specialty—the rather that it has been, of all
their characters, the one most denied. I constantly see that the same
thing takes place in the estimation formed by the modern public of the
work of almost any true person, living or dead. It is not needful to state
here the causes of such error: but the fact is indeed so, that precisely the
distinctive root and leading force of any true man’s work and way are the
things denied concerning him.
And in these books of mine, their distinctive character, as essays on art,
is their bringing everything to a root in human passion or human hope.
Arising first not in any desire to explain the principles of art, but in the
endeavor to defend an individual painter from injustice, they have been
colored throughout,—nay, continually altered in shape, and even warped
and broken, by digressions respecting social questions, which had for me
an interest tenfold greater than the work I had been forced into
undertaking. Every principle of painting which I have stated is traced to
some vital or spiritual fact; and in my works on architecture the
preference accorded finally to one school over another, is founded on a
comparison of their influences on the life of the workman—a question by
all other writers on the subject of architecture wholly forgotten or
despised.
§ 8. The essential connection of the power of landscape with human
emotion is not less certain, because in many impressive pictures the link
is slight or local. That the connection should exist at a single point is all
that we need. The comparison with the dress of the body may be carried
out into the extremest parallelism. It may often happen that no part of
the figure wearing the dress is discernible, nevertheless, the perceivable
fact that the drapery is worn by a figure makes all the difference. In one
of the most sublime figures in the world this is actually so: one of the
fainting Marys in Tintoret’s Crucifixion has cast her mantle over her head,
and her face is lost in its shade, and her whole figure veiled in folds of
gray. But what the difference is between that gray woof, that gathers
round her as she falls, and the same folds cast in a heap upon the
ground, that difference, and more, exists between the power of Nature
through which humanity is seen, and her power in the desert. Desert—
whether of leaf or sand—true desertness is not in the want of leaves, but
of life. Where humanity is not, and was not, the best natural beauty is
more than vain. It is even terrible; not as the dress cast aside from the
body; but as an embroidered shroud hiding a skeleton.
§ 9. And on each side of a right feeling in this matter there lie, as
usual, two opposite errors.
The first, that of caring for man only; and for the rest of the universe,
little, or not at all, which, in a measure, was the error of the Greeks and
Florentines; the other, that of caring for the universe only;—for man, not
at all,—which, in a measure, is the error of modern science, and of the
Art connecting itself with such science.
The degree of power which any man may ultimately possess in
landscape-painting will depend finally on his perception of this influence.
If he has to paint the desert, its awfulness—if the garden, its
gladsomeness—will arise simply and only from his sensibility to the story
of life. Without this he is nothing but a scientific mechanist; this, though
it cannot make him yet a painter, raises him to the sphere in which he
may become one. Nay, the mere shadow and semblance of this have
given dangerous power to works in all other respects unnoticeable; and
the least degree of its true presence has given value to work in all other
respects vain.
The true presence, observe, of sympathy with the spirit of man. Where
this is not, sympathy with any higher spirit is impossible.
For the directest manifestation of Deity to man is in His own image,
that is, in man.
§ 10. “In his own image. After his likeness.” Ad imaginem et
similitudinem Suam. I do not know what people in general understand by
those words. I suppose they ought to be understood. The truth they
contain seems to lie at the foundation of our knowledge both of God and
man; yet do we not usually pass the sentence by, in dull reverence,
attaching no definite sense to it at all? For all practical purpose, might it
not as well be out of the text?
I have no time, nor much desire, to examine the vague expressions of
belief with which the verse has been encumbered. Let us try to find its
only possible plain significance.
§ 11. It cannot be supposed that the bodily shape of man resembles,
or resembled, any bodily shape in Deity. The likeness must therefore be,
or have been, in the soul. Had it wholly passed away, and the Divine soul
been altered into a soul brutal or diabolic, I suppose we should have
been told of the change. But we are told nothing of the kind. The verse
still stands as if for our use and trust. It was only death which was to be
our punishment. Not change. So far as we live, the image is still there;
defiled, if you will; broken, if you will; all but effaced, if you will, by death
and the shadow of it. But not changed. We are not made now in any
other image than God’s. There are, indeed, the two states of this image—
the earthly and heavenly, but both Adamite, both human, both the same
likeness; only one defiled, and one pure. So that the soul of man is still a
mirror, wherein may be seen, darkly, the image of the mind of God.
These may seem daring words. I am sorry that they do; but I am
helpless to soften them. Discover any other meaning of the text if you are
able;—but be sure that it is a meaning—a meaning in your head and
heart;—not a subtle gloss, nor a shifting of one verbal expression into
another, both idealess. I repeat, that, to me, the verse has, and can have,
no other signification than this—that the soul of man is a mirror of the
mind of God. A mirror dark, distorted, broken, use what blameful words
you please of its state; yet in the main, a true mirror, out of which alone,
and by which alone, we can know anything of God at all.
“How?” the reader, perhaps, answers indignantly. “I know the nature of
God by revelation, not by looking into myself.”
Revelation to what? To a nature incapable of receiving truth? That
cannot be; for only to a nature capable of truth, desirous of it,
distinguishing it, feeding upon it, revelation is possible. To a being
undesirous of it, and hating it, revelation is impossible. There can be
none to a brute, or fiend. In so far, therefore, as you love truth, and live
therein, in so far revelation can exist for you;—and in so far, your mind is
the image of God’s.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st Edition Matt Neuburg

  • 1.
    Programming Ios 4Fundamentals Of Iphone Ipad And Ipod Touch Development 1st Edition Matt Neuburg download https://ebookbell.com/product/programming-ios-4-fundamentals-of- iphone-ipad-and-ipod-touch-development-1st-edition-matt- neuburg-2269492 Explore and download more ebooks at ebookbell.com
  • 2.
    Here are somerecommended products that we believe you will be interested in. You can click the link to download. Programming Ios 4 Neuburg Matt https://ebookbell.com/product/programming-ios-4-neuburg-matt-10509378 Programming Ios 4 Matt Neuburg https://ebookbell.com/product/programming-ios-4-matt-neuburg-42957514 Programming Ios 4 Matt Neuburg https://ebookbell.com/product/programming-ios-4-matt-neuburg-42918746 Advanced Ios 4 Programming Developing Mobile Applications For Apple Iphone Ipad And Ipod Touch 1st Edition Maher Ali https://ebookbell.com/product/advanced-ios-4-programming-developing- mobile-applications-for-apple-iphone-ipad-and-ipod-touch-1st-edition- maher-ali-2031638
  • 3.
    Ios 4 ProgrammingCookbook Solutions Examples For Iphone Ipad And Ipod Touch Apps 1st Edition Vandad Nahavandipoor https://ebookbell.com/product/ios-4-programming-cookbook-solutions- examples-for-iphone-ipad-and-ipod-touch-apps-1st-edition-vandad- nahavandipoor-2372508 Ios 4 Programming Cookbook Vandad Nahavandipoor https://ebookbell.com/product/ios-4-programming-cookbook-vandad- nahavandipoor-31832786 Learn Ios 11 Programming With Swift 4 2nd Edition Craig Clayton https://ebookbell.com/product/learn-ios-11-programming-with- swift-4-2nd-edition-craig-clayton-38506028 Mastering Ios 11 Programming Build Professionalgrade Ios Applications With Swift 4 And Xcode 9 Source Code Wals https://ebookbell.com/product/mastering-ios-11-programming-build- professionalgrade-ios-applications-with-swift-4-and-xcode-9-source- code-wals-6856012 Mastering Ios 14 Programming Build Professionalgrade Ios 14 Applications With Swift 53 And Xcode 124 4th Edition Mario Eguiluz Alebicto Chris Barker Donny Wals https://ebookbell.com/product/mastering-ios-14-programming-build- professionalgrade-ios-14-applications-with-swift-53-and-xcode-124-4th- edition-mario-eguiluz-alebicto-chris-barker-donny-wals-23900324
  • 6.
    Programming iOS 4 byMatt Neuburg Copyright © 2011 Matt Neuburg. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Brian Jepson Production Editor: Teresa Elsey Proofreader: Nancy Kotary Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: May 2011: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming iOS 4, the image of a kingbird, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-1-449-38843-0 [LSI] 1305160942
  • 7.
    Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Part I. Language 1. Just Enough C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Compilation, Statements, and Comments 4 Variable Declaration, Initialization, and Data Types 6 Structs 8 Pointers 10 Arrays 11 Operators 13 Flow Control and Conditions 15 Functions 19 Pointer Parameters and the Address Operator 22 Files 24 The Standard Library 27 More Preprocessor Directives 27 Data Type Qualifiers 28 2. Object-Based Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Objects 31 Messages and Methods 32 Classes and Instances 33 Class Methods 36 Instance Variables 37 The Object-Based Philosophy 39 3. Objective-C Objects and Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 An Instance Reference Is a Pointer 43 Instance References, Initialization, and nil 44 v
  • 8.
    Instance References andAssignment 47 Instance References and Memory Management 48 Messages and Methods 49 Sending a Message 50 Declaring a Method 51 Nesting Method Calls 52 No Overloading 52 Parameter Lists 53 Unrecognized Selectors 53 Typecasting and the id Type 55 Messages as Data Type 58 C Functions and Struct Pointers 59 Blocks 61 4. Objective-C Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Class and Superclass 65 Interface and Implementation 66 Header File and Implementation File 68 Class Methods 71 The Secret Life of Classes 71 5. Objective-C Instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 How Instances Are Created 73 Ready-Made Instances 73 Instantiation from Scratch 74 Nib-Based Instantiation 77 Polymorphism 78 The Keyword self 79 The Keyword super 82 Instance Variables and Accessors 84 Key–Value Coding 86 Properties 87 How to Write an Initializer 89 Part II. IDE 6. Anatomy of an Xcode Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 New Project 96 The Project Window 97 The Navigator Pane 99 The Utilities Pane 103 The Editor 104 vi | Table of Contents
  • 9.
    The Project Fileand Its Dependents 106 The Target 109 Build Phases 109 Build Settings 110 Configurations 111 Schemes and Destinations 112 From Project to App 115 Build Settings 117 Property List Settings 117 Nib Files 118 Other Resources 118 Code 120 Frameworks and SDKs 121 7. Nib Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 A Tour of the Nib-Editing Interface 125 The Dock 127 Canvas 128 Inspectors and Libraries 130 Nib Loading and File’s Owner 132 Default Instances in the Main Nib File 133 Making and Loading a Nib 134 Outlet Connections 135 More Ways to Create Outlets 139 More About Outlets 141 Action Connections 142 Additional Initialization of Nib-Based Instances 146 8. Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 The Documentation Window 150 Class Documentation Pages 152 Sample Code 155 Other Resources 156 Quick Help 156 Symbols 157 Header Files 157 Internet Resources 158 9. Life Cycle of a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Choosing a Device Architecture 159 Localization 162 Editing Your Code 163 Autocompletion 164 Table of Contents | vii
  • 10.
    Snippets 165 Live SyntaxChecking 166 Navigating Your Code 166 Debugging 169 Caveman Debugging 169 The Xcode Debugger 171 Static Analyzer 176 Clean 177 Running in the Simulator 177 Running on a Device 178 Device Management 181 Version Control 181 Instruments 184 Distribution 184 Ad Hoc Distribution 186 Final App Preparations 187 Icons in the App 188 Other Icons 189 Launch Images 189 Screenshots 190 Property List Settings 191 Submission to the App Store 192 Part III. Cocoa 10. Cocoa Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Subclassing 197 Categories 200 Splitting a Class 201 Private Method Declarations 201 Protocols 202 Optional Methods 206 Some Foundation Classes 208 Useful Structs and Constants 208 NSString and Friends 208 NSDate and Friends 210 NSNumber 211 NSValue 211 NSData 212 Equality and Comparison 212 NSIndexSet 213 NSArray and NSMutableArray 213 viii | Table of Contents
  • 11.
    NSSet and Friends215 NSDictionary and NSMutableDictionary 215 NSNull 217 Immutable and Mutable 217 Property Lists 218 The Secret Life of NSObject 218 11. Cocoa Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Reasons for Events 224 Subclassing 224 Notifications 226 Receiving a Built-In Notification 226 Unregistering 228 NSTimer 228 Delegation 229 Data Sources 232 Actions 233 The Responder Chain 237 Deferring Responsibility 238 Nil-Targeted Actions 238 Application Lifetime Events 239 Swamped by Events 243 12. Accessors and Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Accessors 249 Key–Value Coding 251 Memory Management 254 The Golden Rules of Memory Management 255 How Cocoa Objects Manage Memory 257 Memory Management of Instance Variables 260 Instance Variable Memory Management Policies 263 Autorelease 264 Nib Loading and Memory Management 266 Memory Management Comments on Earlier Examples 267 Memory Management of Pointer-to-Void Context Info 269 Memory Management of C Struct Pointers 270 Properties 271 13. Data Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Model–View–Controller 277 Instance Visibility 279 Visibility by Instantiation 280 Visibility by Relationship 281 Table of Contents | ix
  • 12.
    Global Visibility 281 Notifications282 Key–Value Observing 284 Part IV. Views 14. Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 The Window 293 Subview and Superview 295 Frame 298 Bounds and Center 299 Layout 302 Transform 305 Visibility and Opacity 308 15. Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 UIImage and UIImageView 311 UIImage and Graphics Contexts 313 CGImage 315 Drawing a UIView 318 Graphics Context State 320 Paths 321 Clipping 325 Gradients 326 Colors and Patterns 328 Graphics Context Transforms 330 Shadows 332 Points and Pixels 332 Content Mode 333 16. Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 View and Layer 336 Layers and Sublayers 337 Manipulating the Layer Hierarchy 339 Positioning a Sublayer 339 CAScrollLayer 340 Layout of Sublayers 341 Drawing in a Layer 341 Contents Image 341 Contents on Demand 342 Contents Resizing and Positioning 343 Layers that Draw Themselves 345 x | Table of Contents
  • 13.
    Transforms 346 Depth 350 Transformsand Key–Value Coding 352 Shadows, Borders, and More 353 Layers and Key–Value Coding 354 17. Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 Drawing, Animation, and Threading 358 UIImageView Animation 361 View Animation 362 Animation Blocks 362 Modifying an Animation Block 363 Transition Animations 366 Block-Based View Animation 368 Implicit Layer Animation 371 Animation Transactions 372 Media Timing Functions 373 Core Animation 374 CABasicAnimation and Its Inheritance 375 Using a CABasicAnimation 376 Keyframe Animation 379 Making a Property Animatable 380 Grouped Animations 381 Transitions 385 The Animations List 386 Actions 389 What an Action Is 389 The Action Search 390 Hooking Into the Action Search 391 Nonproperty Actions 394 18. Touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Touch Events and Views 398 Receiving Touches 400 Restricting Touches 401 Interpreting Touches 402 Gesture Recognizers 408 Distinguishing Gestures Manually 408 Gesture Recognizer Classes 412 Multiple Gesture Recognizers 416 Subclassing Gesture Recognizers 418 Gesture Recognizer Delegate 419 Touch Delivery 422 Table of Contents | xi
  • 14.
    Hit-Testing 423 Initial TouchEvent Delivery 427 Gesture Recognizer and View 427 Touch Exclusion Logic 429 Recognition 430 Touches and the Responder Chain 431 Part V. Interface 19. View Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 Creating a View Controller 437 Manual View Controller, Manual View 438 Manual View Controller, Nib View 441 Nib-Instantiated View Controller 443 No View 445 Up-Shifted Root View 446 Rotation 447 Initial Orientation 448 Rotation Events 452 Modal Views 453 Modal View Configuration 454 Modal View Presentation 456 Modal View Dismissal 457 Modal Views and Rotation 459 Tab Bar Controllers 461 Tab Bar Item Images 462 Configuring a Tab Bar Controller 463 Navigation Controllers 464 Bar Button Items 466 Configuring a Navigation Interface 468 Navigation Interface Rotation 474 View Controller Lifetime Events 476 View Controller Memory Management 477 20. Scroll Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 Creating a Scroll View 482 Scrolling 484 Paging 487 Tiling 488 Zooming 491 Zooming Programmatically 493 Zooming with Detail 493 xii | Table of Contents
  • 15.
    Scroll View Delegate499 Scroll View Touches 500 Scroll View Performance 503 21. Table Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 Table View Cells 507 Built-In Cell Styles 508 Custom Cells 512 Table View Data 517 The Three Big Questions 518 Table View Sections 521 Refreshing Table View Data 524 Variable Row Heights 526 Table View Selection 528 Table View Scrolling and Layout 533 Table View Searching 533 Table View Editing 539 Deleting Table Items 541 Editable Content in Table Items 543 Inserting Table Items 544 Rearranging Table Items 546 22. Popovers and Split Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549 Presenting a Popover 550 Managing a Popover 553 Dismissing a Popover 554 Automatic Popovers 557 Split Views 558 23. Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563 UILabel 564 UITextField 565 Editing and the Keyboard 568 Configuring the Keyboard 572 Text Field Delegate and Control Event Messages 572 The Text Field Menu 574 UITextView 576 Core Text 579 24. Web Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 Loading Content 588 Communicating with a Web View 593 Table of Contents | xiii
  • 16.
    25. Controls andOther Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597 UIActivityIndicatorView 597 UIProgressView 598 UIPickerView 600 UISearchBar 602 UIControl 604 UISwitch 605 UIPageControl 605 UIDatePicker 606 UISlider 609 UISegmentedControl 612 UIButton 614 Custom Controls 617 Bars 620 UINavigationBar 621 UIToolbar 623 UITabBar 623 26. Modal Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629 Alert View 630 Action Sheet 631 Dialog Alternatives 635 Local Notifications 636 Part VI. Some Frameworks 27. Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643 System Sounds 643 Audio Session 644 Audio Player 648 Remote Control of Your Sound 650 Playing Sound in the Background 651 Further Topics in Sound 653 28. Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655 MPMoviePlayerController 656 MPMoviePlayerViewController 660 UIVideoEditorController 661 Further Topics in Video 662 29. Music Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 Exploring the Music Library 667 xiv | Table of Contents
  • 17.
    The Music Player671 The Music Picker 675 30. Photo Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679 UIImagePickerController 679 Choosing from the Photo Library 680 Using the Camera 681 The Assets Library Framework 684 31. Address Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 Address Book Database 687 Address Book Interface 690 ABPeoplePickerNavigationController 690 ABPersonViewController 692 ABNewPersonViewController 692 ABUnknownPersonViewController 693 32. Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695 Calendar Database 695 Calendar Interface 700 33. Mail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703 Mail Message 703 SMS Message 704 34. Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705 Presenting a Map 705 Annotations 706 Overlays 712 35. Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717 Location 717 Heading and Course 719 Acceleration 720 Shake Events 721 UIAccelerometer 722 Core Motion 725 Table of Contents | xv
  • 18.
    Part VII. FinalTopics 36. Persistent Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729 The Sandbox 729 Basic File Operations 730 Saving and Reading Files 731 User Defaults 733 File Sharing 735 Document Types 735 Handing Off a Document 737 XML 740 SQLite 746 Image File Formats 747 37. Basic Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751 HTTP Requests 751 Bonjour 757 Push Notifications 759 Beyond Basic Networking 760 38. Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761 The Main Thread 761 Why Threading Is Hard 764 Three Ways of Threading 765 Manual Threads 766 NSOperation 768 Grand Central Dispatch 772 Threads and App Backgrounding 775 39. Undo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779 The Undo Manager 779 The Undo Interface 782 The Undo Architecture 785 40. Epilogue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789 xvi | Table of Contents
  • 19.
    Preface Aut lego velscribo; doceo scrutorve sophian. —Sedulius Scottus With the advent of version 2 of the iPhone system, Apple proved they could do a re- markable thing — adapt their existing Cocoa computer application programming framework to make applications for a touch-based device with limited memory and speed and a dauntingly tiny display. The resulting Cocoa Touch framework, in fact, turned out to be in many ways better than the original Cocoa. A programming framework has a kind of personality, an overall flavor that provides an insight into the goals and mindset of those who created it. When I first encountered Cocoa Touch, my assessment of its personality was: “Wow, the people who wrote this are really clever!” On the one hand, the number of built-in interface widgets was se- verely and deliberately limited; on the other hand, the power and flexibility of some of those widgets, especially such things as UITableView, was greatly enhanced over their Mac OS X counterparts. Even more important, Apple created a particularly brilliant way (UIViewController) to help the programmer make entire blocks of interface come and go and supplant one another in a controlled, hierarchical manner, thus allowing that tiny iPhone display to unfold virtually into multiple interface worlds within a single app without the user becoming lost or confused. Even more impressive, Apple took the opportunity to recreate and rationalize Cocoa from the ground up as Cocoa Touch. Cocoa itself is very old, having begun life as NeXTStep before Mac OS X even existed. It has grown by accretion and with a certain conservatism in order to maintain something like backward compatibility. With Cocoa Touch, on the other hand, Apple had the opportunity to throw out the baby with the bath water, and they seized this opportunity with both hands. So, although Cocoa Touch is conceptually based on Mac OS X Cocoa, it is very clearly not Mac OS X Cocoa, nor is it limited or defined by Mac OS X Cocoa. It’s an inde- pendent creature, a leaner, meaner, smarter Cocoa. I could praise Cocoa Touch’s de- liberate use of systematization (and its healthy respect for Occam’s Razor) through numerous examples. Where Mac OS X’s animation layers are glommed onto views as a kind of afterthought, a Cocoa Touch view always has an animation layer counterpart. xvii
  • 20.
    Memory management policies,such as how top-level objects are managed when a nib loads, are simplified and clarified. And so on. At the same time, Cocoa Touch is still a form of Cocoa. It still requires a knowledge of Objective-C. It is not a scripting language; it is certainly not aimed at nonprogrammers, like HyperCard’s HyperTalk or Apple’s AppleScript. It is still huge and complicated. In fact, it’s rather difficult. Meanwhile, Cocoa Touch itself evolves and changes. The iPhone System 2 matured into the iPhone System 3. Then there was a sudden sally in a new direction when the iPad introduced a larger screen and iPhone System 3.2. The iPhone 4 and its double- resolution Retina display also ran on a major system increment, now dubbed iOS 4. Every one of these changes has brought new complexities for the programmer to deal with. To give just one simple example, users rightly complained that switching between apps on the iPhone meant quitting one app and launching another. So Apple gave the iPhone 4 the power of multitasking; the user can switch away from an app and then return to it later to find it still running and in the state it was left previously. All well and good, but now programmers must scurry to make their apps compatible with mul- titasking, which is not at all trivial. The popularity of the iPhone, with its largely free or very inexpensive apps, and the subsequent popularity of the iPad, have brought and will continue to bring into the fold many new programmers who see programming for these devices as worthwhile and doable, even though they may not have felt the same way about Mac OS X. Apple’s own annual WWDC developer conventions have reflected this trend, with their em- phasis shifted from Mac OS X to iOS instruction. The widespread eagerness to program iOS, however, though delightful on the one hand, has also fostered a certain tendency to try to run without first learning to walk. iOS gives the programmer mighty powers that can seem as limitless as imagination itself, but it also has fundamentals. I often see questions online from programmers who are evidently deep into the creation of some interesting app, but who are stymied in a way that reveals quite clearly that they are unfamiliar with the basics of the very world in which they are so happily cavorting. It is this state of affairs that has motivated me to write this book, which is intended to ground the reader in the fundamentals of iOS. I love Cocoa and have long wished to write about it, but it is iOS and its popularity that has given me a proximate excuse to do so. Indeed, my working title was “Fundamentals of Cocoa Touch Programming.” HereIhaveattemptedtomarshalandexpound,inwhatIhopeisapedagogicallyhelpful and instructive yet ruthlessly Euclidean and logical order, the principles on which sound iOS programming rests, including a good basic knowledge of Objective-C (start- ing with C itself) and the nature of object-oriented programming, advice on the use of the tools, the full story on how Cocoa objects are instantiated, referred to, put in com- munication with one another, and managed over their lifetimes, and a survey of the primary interface widgets and other common tasks. My hope, as with my previous xviii | Preface
  • 21.
    books, is thatyou will both read this book cover to cover (learning something new often enough to keep you turning the pages) and keep it by you as a handy reference. This book is not intended to disparage Apple’s own documentation and example projects. They are wonderful resources and have become more wonderful as time goes on. I have depended heavily on them in the preparation of this book. But I also find that they don’t fulfill the same function as a reasoned, ordered presentation of the facts. The online documentation must make assumptions as to how much you already know; it can’t guarantee that you’ll approach it in a given order. And online documentation is more suitable to reference than to instruction. A fully written example, no matter how well commented, is difficult to follow; it demonstrates, but it does not teach. A book, on the other hand, has numbered chapters and sequential pages; I can assume you know C before you know Objective-C for the simple reason that Chapter 1 precedes Chapter 2. And along with facts, I also bring to the table a degree of experience, which I try to communicate to you. Throughout this book you’ll see me referring to “common beginner mistakes”; in most cases, these are mistakes that I have made myself, in ad- dition to seeing others make them. I try to tell you what the pitfalls are because I assume that, in the course of things, you will otherwise fall into them just as naturally as I did as I was learning. You’ll also see me construct many examples piece by piece or extract and explain just one tiny portion of a larger app. It is not a massive finished program that teaches programming, but an exposition of the thought process that developed that program. It is this thought process, more than anything else, that I hope you will gain from reading this book. iOS is huge, massive, immense. It’s far too big to be encompassed in a book even of this size. And in any case, that would be inappropriate and unnecessary. There are entire areas of Cocoa Touch that I have ruthlessly avoided discussing. Some of them would require an entire book of their own. Others you can pick up well enough, when the time comes, from the documentation. This book is only a beginning — the funda- mentals. But I hope that it will be the firm foundation that will make it easier for you to tackle whatever lies beyond, in your own fun and rewarding iOS programming fu- ture. In closing, some version numbers, so that you know what assumptions I am making. At the time I started writing this book, system versions 3.1.3 (on the iPhone) and 3.2 (on the iPad) were most recent. As I was working on the book, iOS 4 and the iPhone 4 came into being, but it didn’t yet run on the iPad. Subsequently iOS 4.2 emerged: the first system able to run on both the iPhone and the iPad. At the same time, Xcode was improved up to 3.2.5. Then, just in time for my final revisions, Xcode 3.2.6 and iOS 4.3 were released, along withthefirstpublicversionofthelong-awaitedXcode4.Xcode4isathoroughoverhaul of the IDE: menus, windows, and preferences are quite different from Xcode 3.2.x. At the same time, both Xcode 4 and Xcode 3.2.x can coexist on the same machine and can be used to work on the same project; moreover, Xcode 3.2.x has some specialized Preface | xix
  • 22.
    capabilities that Xcode4 lacks, so some long-standing developers may well continue to use it. This situation presents a dilemma for an author describing the development process. However, for iOS programming, I recommend adoption of Xcode 4, and this book assumes that you have adopted it. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter- mined by context. This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. xx | Preface
  • 23.
    We appreciate, butdo not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming iOS 4 by Matt Neuburg (O’Reilly). Copyright 2011 Matt Neuburg, 978-1-449-38843-0.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. Safari® Books Online Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly. Withasubscription,youcanreadanypageandwatchanyvideofromourlibraryonline. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, down- load chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features. O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other pub- lishers, sign up for free at http://my.safaribooksonline.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at: http://oreilly.com/catalog/0636920010258/ To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Preface | xxi
  • 24.
    Follow us onTwitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments It’s a poor craftsman who blames his tools. No blame attaches to the really great tools by which I have been assisted in the writing of this book. I am particularly grateful to the Unicomp Model M keyboard (http://pckeyboard.com), without which I could not have produced so large a book so painlessly. I was also aided by wonderful software, including TextMate (http://macromates.com) and AsciiDoc (http://www.methods.co.nz/ asciidoc). BBEdit (http://www.barebones.com) helped with its diff display. Screenshots were created with Snapz Pro X (http://www.ambrosiasw.com) and GraphicConverter (http://www.lemkesoft.com); diagrams were drawn with OmniGraffle (http://www.om nigroup.com). The splendid O’Reilly production process converted my AsciiDoc text files into PDF while I worked, allowing me to proofread in simulated book format. Were it not for this, and the Early Release program that permitted me to provide my readers with periodic updates of the book as it grew, I would never have agreed to undertake this project in the first place. I would like particularly to thank Tools maven Abby Fox for her constant assistance. I have taken advice from two tech reviewers, Dave Smith and David Rowland, and have been assisted materially and spiritually by many readers who submitted errata and encouragement. I was particularly fortunate in having Brian Jepson as editor; he pro- vided enthusiasm for the O’Reilly tools and the electronic book formats, a watchful eye, and a trusting attitude; he also endured the role of communications pipeline when I needed to prod various parts of the O’Reilly machine. I have never written an O’Reilly book without the help of Nancy Kotary, and I didn’t intend to start now; her sharp eye has smoothed the bristles of my punctuation-laden style. For errors that remain, I take responsibility, of course. xxii | Preface
  • 25.
    PART I Language Apple hasprovided a vast toolbox for programming iOS to make an app come to life and behave the way you want it to. That toolbox is the API (application programming interface). To use the API, you must speak the API’s language. That language, for the most part, is Objective-C, which itself is built on top of C; some pieces of the API use C itself. This part of the book instructs you in the basics of these languages: • Chapter 1 explains C. In general, you will probably not need to know all the ins and outs of C, so this chapter restricts itself to those aspects of C that you need to know in order to use both Objective-C and the C-based areas of the API. • Objective-C adds object-based programming features to C. Chapter 2 discusses object-based programming in general architectural terms. It also explains some extremely important terms that will be used throughout the book, along with the concepts that lie behind them. • Chapter 3 introduces the basic syntax of Objective-C. • Chapter 4 continues the explanation of Objective-C, discussing the nature of Objective-C classes, with emphasis on how to create a class in code. • Chapter 5 completes the introduction to Objective-C, discussing how instances are created and initialized, along with an explanation of such related topics as polymorphism, instance variables, accessors, self and super, key–value coding, and properties. Even at this point, our discussion of Objective-C is not yet complete; we’ll return in Part III to a description of further aspects of the language: those that are particularly bound up with the Cocoa frameworks.
  • 26.
    CHAPTER 1 Just EnoughC Do you believe in C? Do you believe in anything that has to do with me? —Leonard Bernstein and Stephen Schwartz, Mass To program for iOS, you need some knowledge of the C programming language, for two reasons: • Most of your iOS programming will be in the Objective-C language, and Objective- C is a superset of C. This means that Objective-C presupposes C; everything that is true of C trickles up to Objective-C. A common mistake is to forget that “Objective-C is C” and to neglect a basic understanding of C. • Some of the iOS API involves C rather than Objective-C. Even in Objective-C code, you often need to use C data structures and C function calls. For example, a rec- tangle is represented as a CGRect, which is a C struct, and to create a CGRect from four numbers you call CGRectMake, which is a C function. The iOS API docu- mentation will very often show you C expressions and expect you to understand them. The best way to learn C is to read The C Programming Language (PTR Prentice Hall, 1988) by Brian W. Kernighan and Dennis M. Ritchie, commonly called K&R (Ritchie was the creator of C). It is one of the best computer books ever written: brief, dense, and stunningly precise and clear. K&R is so important for effective iOS (and Mac OS X) programming that I keep a physical copy beside me at all times while coding, and I recommend that you do the same. Another useful manual is The C Book, by Mike Banahan, Declan Brady and Mark Doran, available online at http://publications.gbdirect .co.uk/c_book/. You don’t have to know all about C in order to use Objective-C effectively, though; and that’s a good thing. C is not a large or difficult language, but it has some tricky corners and can be extremely subtle, powerful, and low-level. Also, it would be im- possible, and unnecessary, for me to describe all of C in a single chapter. C is described far more fully and correctly in K&R, The C Book, and elsewhere than I could possibly 3
  • 27.
    do it. Sooneror later, you’re probably going to have technical questions about C that this chapter doesn’t (and shouldn’t) make any attempt to answer. So I emphasize that you really, really ought to have K&R or something similar at hand and resort to it as needed. What I can do, and what this chapter will attempt to do, is tell you what aspects of C are important to understand at the outset, before you even start using Objective-C for iOS programming. That’s why this chapter is “Just Enough C”: it’s just enough to get you going, comfortably and safely. If you know no C at all, I suggest that, as an accompaniment to this chapter, you also read parts of K&R (think of this as “C: The Good Parts Version”). Here’s my proposed K&R syllabus: • Quickly skim K&R Chapter 1, the tutorial. • Carefully read K&R Chapters 2 through 4. • Read the first three sections of K&R Chapter 5 on pointers and arrays. You don’t need to read the rest of Chapter 5 because you won’t typically be doing any pointer arithmetic, but you do need to understand clearly what a pointer is, as Objective- C is all about objects and every reference to an object is a pointer; you’ll be seeing and using that * character constantly. • Read also the first section of K&R Chapter 6, on structures (structs); as a beginner, you probably won’t define any structs, but you will use them quite a lot, so you’ll need to know the notation (for example, as I’ve already said, a CGRect is a struct). • Glance over K&R Appendix B, which covers the standard library, because you may find yourself making certain standard library calls, such as the mathematical func- tions; forgetting that the library exists is a typical beginner mistake. Just to make things a little more confusing, the C defined in K&R is not precisely the C that forms the basis of Objective-C. Developments subsequent to K&R have resulted in further C standards (ANSI C, C89, C99), and the Xcode compiler extends the C language in its own ways. By default, Xcode projects are treated as C99 (though you could specify another C standard if you really wanted to). Fortunately, the most im- portant differences between K&R’s C and Xcode’s C are small, convenient improve- ments that are easily remembered, so K&R remains the best and most reliable C ref- erence. Compilation, Statements, and Comments C is a compiled language. You write your program as text; to run the program, things proceed in two stages. First your text is compiled into machine instructions; then those machine instructions are executed. Thus, as with any compiled language, you can make two kinds of mistake: 4 | Chapter 1: Just Enough C
  • 28.
    • Any purelysyntactic errors (meaning that you spoke the C language incorrectly) will be caught by the compiler, and the program won’t even begin to run. • If your program gets past the compiler, then it will run, but there is no guarantee that you haven’t made some other sort of mistake, which can be detected only by noticing that the program doesn’t behave as intended. The C compiler is fussy, but you should accept its interference with good grace. The compiler is your friend: learn to love it. It may emit what looks like an irrelevant or incomprehensible error message, but when it does, the fact is that you’ve done some- thing wrong and the compiler has helpfully caught it for you. Also, the compiler can warn you if something seems like a possible mistake, even though it isn’t strictly illegal; these warnings, which differ from outright errors, are also helpful and should not be ignored. I have said that running a program requires a preceding stage: compilation. But in fact there is a third stage that precedes compilation: preprocessing. (It doesn’t really matter whether you think of preprocessing as a stage preceding compilation or as the first stage of compilation.) Preprocessing modifies your text, so when your text is handed to the compiler, it is not identical to the text you wrote. Preprocessing might sound tricky and intrusive, but in fact it proceeds only according to your instructions and is helpful for making your code clearer and more compact. C is a statement-based language; every statement ends in a semicolon. (Forgetting the semicolon is a common beginner’s mistake and is liable to get you a completely irrel- evant and incomprehensible error message from the compiler.) For readability, pro- grams are mostly written with one statement per line, but this is by no means a hard and fast rule: long statements (which, unfortunately, arise very commonly because of Objective-C’s verbosity) are commonly split over multiple lines, and extremely short statements are sometimes written two or three to a line. You cannot split a line just anywhere, however; for example, a literal string can’t contain a return character. In- dentation is linguistically meaningless and is purely a matter of convention (and C programmers argue over those conventions with near-religious fervor); Xcode helps “intelligently” by indenting automatically, and you can use its automatic indentation both to keep your code readable and to confirm that you’re not making any basic syntactic mistakes. Comments are delimited in K&R C by /* ... */; the material between the delimiters can consist of multiple lines (K&R 1.2). In modern versions of C, a comment also can be denoted by two slashes (//); the rule is that if two slashes appear, they and everything after them on the same line are ignored: int lower = 0; // lower limit of temperature table These are sometimes called C++-style comments and are much more convenient for brief comments than the K&R comment syntax. Compilation, Statements, and Comments | 5
  • 29.
    Throughout the Clanguage (and therefore, throughout Objective-C as well), capitali- zation matters. All names are case-sensitive. There is no such data type as Int; it’s lowercase “int.” If you declare an int called lower and then try to speak of the same variable as Lower, the compiler will complain. By convention, variable names tend to start with a lowercase letter. Variable Declaration, Initialization, and Data Types C is a strongly typed language. Every variable must be declared, indicating its data type, before it can be used. Declaration can also involve explicit initialization; a variable that is declared but not explicitly initialized is of uncertain value (and should be regarded as dangerous until it is initialized). In K&R C, declarations must precede all other statements, but in modern versions of C, this rule is relaxed so that you don’t have to declare a variable until just before you start using it. The usual convention is thus to declare a variable and assign it a value as it makes its first appearance on the scene: int height = 2; int width = height * 2; height = height + 1; int area = height * width; The basic built-in C data types are all numeric: char (one byte), int (four bytes), float and double (floating-point numbers), and varieties such as short (short integer), long (long integer), unsigned short, and so on. iOS makes use of some further numeric types derived from the C numeric types (by way of the typedef statement, K&R 6.7); the most important of these are NSInteger (along with NSUInteger) and CGFloat. You don’t Choosing a Compiler The compiler situation in Xcode is rather complicated. Originally, Xcode’s compiler was the free open source GCC (http://gcc.gnu.org). More recently, Xcode has been phasing in use of another free open source compiler, LLVM (http://llvm.org). Changing compilers is scary, so Apple has proceeded in stages, as follows: • GCC is still supported. • A hybrid compiler, LLVM-GCC, provides the advantages of LLVM compilation, but the code is parsed with GCC for maximum backward compatibility. • A pure LLVM compiler (also referred to as Clang) does its own parsing and pro- vides more intelligent and helpful error messages and warnings. As Xcode 3.2.x evolved, LLVM-GCC was eventually considered the best choice, but Apple was hesitant to make it the default compiler, so GCC remained the default. In Xcode 4, LLVM-GCC is the default compiler; both GCC and the pure LLVM compiler are also available. (The choice of compiler is a project-level build setting; seeChapter 6.) 6 | Chapter 1: Just Enough C
  • 30.
    need to usethese explicitly unless an API tells you to, and even when you do, just think of NSInteger as int and CGFloat as float, and you’ll be fine. To cast (or typecast) a variable’s value explicitly to another type, precede the variable’s name with the other type’s name in parentheses: int height = 2; float fheight = (float)height; In that particular example, the explicit cast is unnecessary because the integer value will be cast to a float implicitly as it is assigned to a float variable, but it illustrates the notation. You’ll find yourself typecasting quite a bit in Objective-C, mostly in order to subdue the worries of the compiler (examples appear in Chapter 3). Another form of numeric initialization is the enum (K&R 2.3). It’s a way of assigning names to a sequence of numeric values and is useful when a value represents one of several possible options. The Cocoa API uses this device a lot. For example, the three possible types of status bar animation are defined like this: typedef enum { UIStatusBarAnimationNone, UIStatusBarAnimationFade, UIStatusBarAnimationSlide, } UIStatusBarAnimation; That definition assigns the value 0 to the name UIStatusBarAnimationNone, the value 1 to the name UIStatusBarAnimationFade, and the value 2 to the name UIStatusBar- AnimationSlide. The upshot is, however, that you can use the suggestively meaningful names without caring about, or even knowing, the arbitrary numeric values they rep- resent. It’s a useful idiom, and you may well have reason to define enums in your own code. There appears to be a native text type (a string) in C, but this is something of an illusion; behind the scenes, it is actually a null-terminated array of char. For example, in C you can write a string literal like this: "string" But in fact this is stored as 7 bytes, the numeric (ASCII) equivalents of each letter followed by a byte consisting of 0 to signal the end of the string. This data structure, called a C string, is rather tricky, and if you’re lucky you’ll rarely or never encounter one while programming iOS. In general, when working with strings, you’ll use an Objective-C object type called NSString. An NSString is totally different from a C string; it happens, however, that Objective-C lets you write a literal NSString in a way that looks very like a C string: @"string" Notice the at-sign! This expression is actually a directive to the Objective-C compiler to form an NSString object. A common mistake is forgetting the at-sign, thus causing your expression to be interpreted as a C string, which is a completely different animal. Variable Declaration, Initialization, and Data Types | 7
  • 31.
    Because the notationfor literal NSStrings is modeled on the notation for C strings, it is worth knowing something about C strings, even though you won’t generally en- counter them. For example, K&R lists a number of escaped characters (K&R 2.3), which you can also use in a literal NSString, including the following: n A Unix newline character t A tab character " A quotation mark (escaped to show that this is not the end of the string literal) A backslash NSStrings are natively Unicode-based, but because Objective-C is C, including non-ASCII characters in a literal NSString was, until quite recently, remarkably tricky, and you needed to know about such things as the x and u escape sequences. Now, however, it is perfectly legal to type a bullet or any other non-ASCII character directly into an NSString literal, and you should ignore old Internet postings (and even an occa- sional sentence in Apple’s own documentation) warning that it is not. K&R also mention a notation for concatenating string literals, in which multiple string literals separated only by white space are automatically concatenated and treated as a single string literal. This notation is useful for splitting a long string into multiple lines for legibility, and Objective-C copies this convention for literal NSStrings as well, ex- cept that you have to remember the at-sign: @"This is a big long literal string " @"which I have broken over two lines of code."; Structs C offers few simple native data types, so how are more complex data types made? There are three ways: structures, pointers, and arrays. Both structures and pointers are going tobecrucialwhenyou’reprogrammingiOS.You’relesslikelytoneedaCarray,because Objective-C has its own NSArray object type, but it will arise in a couple of examples later in this book. A C structure, usually called a struct (K&R 6.1), is a compound data type: it combines multiple data types into a single type, which can be passed around as a single entity. Moreover, the elements constituting the compound entity have names and can be ac- cessed by those names through the compound entity, using dot-notation. For example, the iOS documentation tells you that a CGPoint is defined as follows: 8 | Chapter 1: Just Enough C
  • 32.
    struct CGPoint { CGFloatx; CGFloat y; }; typedef struct CGPoint CGPoint; Recall that a CGFloat is basically a float, so this is a compound data type made up of two simple native data types; in effect, a CGPoint has two CGFloat parts, and their names are x and y. (The rather odd-looking last line merely asserts that one can use the term CGPoint instead of the more verbose struct CGPoint.) So we can write: CGPoint myPoint; myPoint.x = 4.3; myPoint.y = 7.1; Just as we can assign to myPoint.x in order to set this part of the struct, we can say my- Point.x to get this part of the struct. It’s as if myPoint.x were the name of a variable. Moreover, an element of a struct can itself be a struct, and the dot-notation can be chained. To illustrate, first note the existence of another iOS struct, CGSize: struct CGSize { CGFloat width; CGFloat height; }; typedef struct CGSize CGSize; Put a CGPoint and a CGSize together and you’ve got a CGRect: struct CGRect { CGPoint origin; CGSize size; }; typedef struct CGRect CGRect; So suppose we’ve got a CGRect variable called myRect, already initialized. Then my- Rect.origin is a CGPoint, and myRect.origin.x is a CGFloat. Similarly, myRect.size is a CGSize, and myRect.size.width is a CGFloat. You could change just the width part of our CGRect directly, like this: myRect.size.width = 8.6; Instead of initializing a struct by assigning to each of its elements, you can initialize it at declaration time by assigning values for all its elements at once, in curly braces, separated by commas, like this: CGPoint myPoint = { 4.3, 7.1 }; The iOS API has many commonly used structs, typically accompanied by convenience functions for working with them. Structs | 9
  • 33.
    Pointers The other bigway that C extends its range of data types is by means of pointers (K&R 5.1). A pointer is an integer (of some size or other) with a meaning: it designates the location in memory where the real data is to be found. Knowing the structure of that data and how to work with it, as well as allocating a block of memory of the required size beforehand and disposing of that block of memory when it’s no longer needed, is a very complicated business. Luckily, this is exactly the sort of complicated business that Objective-C is going to take care of for us. So all you really have to know in order to use pointers is what they are and what notation is used to refer to them. Let’s start with a simple declaration. If we wanted to declare an integer in C, we could say: int i; That line says, “i is an integer.” Now let’s instead declare a pointer to an integer: int* intPtr; That line says, “intPtr is a pointer to an integer.” Never mind how we know there really is going to be an integer at the address designated by this point; here, I’m concerned only with the notation. It is permitted to place the asterisk in the declaration before the name rather than after the type: int *intPtr; I don’t generally use that second form when declaring a pointer, but it does come in handy when declaring several variables of the same type in a single statement. Here’s what I mean. It is legal, though I did not mention this earlier, to declare multiple var- iables of a single type in one statement, like this: int i, j, k; By the same token, it is possible to declare multiple pointers to the same type in one statement by attaching the asterisk to the variable name (repeatedly): int *intPtr1, *intPtr2, *intPtr3; However, the name of the type is still int*. If you are asked what type is intPtr is, the answer is int* (a pointer to an int); the asterisk is part of the name of the type of this variable. If you needed to cast a variable p to this type, you’d cast like this: (int*)p. Pointers are very important in Objective-C, because Objective-C is all about objects (Chapter 2), and every variable referring to an object is itself a pointer. For example, I’ve already mentioned that the Objective-C string type is called NSString. So the way to declare an NSString variable is as a pointer to an NSString: NSString* s; An NSString literal is an NSString value, so we can even declare and initialize this NSString object, thus writing a seriously useful line of Objective-C code: 10 | Chapter 1: Just Enough C
  • 34.
    NSString* s =@"Hello, world!"; In pure C, having declared a pointer-to-integer called intPtr, you are liable to speak later in your code of *intPtr. This notation, outside of a declaration, means “the thing pointed to by the pointer intPtr.” You speak of *intPtr because you wish to access the integer at the far end of the pointer. But in Objective-C, this is generally not the case. In your code, you’ll be treating the pointer to an object as the object. So, for example, having declared s as a pointer to an NSString, you will not then proceed to speak of *s; rather, you will speak simply of s, as if it were the string. All the Objective-C stuff you’ll want to do with an object will expect the pointer, not the object at the far end of the pointer; behind the scenes, Objective-C itself will take care of the messy business of following the pointer to its block of memory and doing whatever needs to be done in that block of memory. This fact is extremely convenient for you as a programmer, but it does cause Objective-C users to speak a little loosely; we tend to say that “s is an NSString,” when of course it is actually a pointer to an NSString. Youmustneverletthisconveniencelullyouintoforgettingthecrucialfactthatapointer is a pointer. The logic of how pointers work is different from the logic of how simple data types work. The difference is particularly evident with assignment. Assignment to a simple data type changes the data value. Assignment to a pointer repoints the pointer. Suppose ptr1 and ptr2 are both pointers, and you say: ptr1 = ptr2; Now ptr1 and ptr2 are pointing at the same thing. Any change to the thing pointed to by ptr1 will also change the thing pointed to by ptr2, because they are the same thing. Meanwhile, whatever ptr1 was pointing to before the assignment is now not being pointed to by ptr1; it might, indeed, be pointed to by nothing (which could be bad). A firm understanding of these facts is crucial when working in Objective-C (Figure 1-1). The most general type of pointer is pointer-to-void (void*), the generic pointer. It is legal to use a generic pointer wherever a specific type of pointer is expected. In effect, pointer- to-void casts away type checking as to what’s at the far end of the pointer. Thus, the following is legal: int* p1; // and pretend p1 has a value void* p2; p2 = p1; p1 = p2; Arrays A C array (K&R 5.3) consists of multiple elements of the same data type. An array declaration states the data type of the elements, followed by the name of the array, along with square brackets containing the number of elements: int arr[3]; // means: arr is an array consisting of 3 ints Arrays | 11
  • 35.
    To refer toan element of an array, use the array’s name followed by the element number in square brackets. The first element of an array is numbered 0. So we can initialize an array by assigning values to each element in turn: int arr[3]; arr[0] = 123; arr[1] = 456; arr[2] = 789; Figure 1-1. Pointers and assignment 12 | Chapter 1: Just Enough C
  • 36.
    Alternatively, you caninitialize an array at declaration time by assigning a list of values in curly braces, just as with a struct. In this case, the size of the array can be omitted from the declaration, because it is implicit in the initialization (K&R 4.9): int arr[] = {123, 456, 789}; Curiously, the name of an array is the name of a pointer (to the first element of the array). Thus, for example, having declared arr as in the preceding examples, you can use arr wherever a value of type int* (a pointer to an int) is expected. This fact is the basis of some highly sophisticated C idioms that you almost certainly won’t need to know about (which is why I don’t recommend that you read any of K&R Chapter 5 beyond section 3). C arrays rarely arise in practice when programming iOS, because you’ll work mostly with the NSArray object type instead. But here’s a case where they do. The function CGContextStrokeLineSegments is declared like this: void CGContextStrokeLineSegments ( CGContextRef c, const CGPoint points[], size_t count ); The second parameter is an array (meaning a C array) of CGPoints. That’s what the square brackets tell you. So to call this function, you’d need to know at least how to make an array of CGPoints. You might do it like this: CGPoint arr[] = {{4,5}, {6,7}, {8,9}, {10,11}}; Having done that, you can pass arr as the second argument in a call to CGContextStroke- LineSegments. Also, a C string, as I’ve already mentioned, is actually an array. For example, the NSString method stringWithUTF8String: takes (according to the documentation) “a NULL-terminated C array of bytes in UTF8 encoding;” but the parameter is declared not as an array, but as a char*. Those are the same thing, and are both ways of saying that this method takes a C string. Operators Arithmetic operators are straightforward (K&R 2.5), but watch out for the rule that “integer division truncates any fractional part.” This rule is the cause of much novice error in C. If you have two integers and you want to divide them in such a way as to get a fractional result, you must represent at least one of them as a float: int i = 3; float f = i/2; // beware! not 1.5 To get 1.5, you should have written i/2.0 or (float)i/2. Operators | 13
  • 37.
    The integer incrementand decrement operators (K&R 2.8), ++ and --, work differently dependingonwhethertheyprecedeorfollowtheirvariable.Theexpression++i replaces the value of i by 1 more than its current value and then uses the resulting value; the expression i++ uses the current value of i and then replaces it with 1 more than its current value. This is one of C’s coolest features. C also provides bitwise operators (K&R 2.9), such as bitwise-and (&) and bitwise-or (|); they operate on the individual binary bits that constitute integers. Of these, the one you are most likely to need is bitwise-or, because the Cocoa API often uses bits as switches when multiple options are to be specified simultaneously. For example, there are various ways in which a UIView can be resized automatically as its superview is resized, and you’re supposed to provide one or more of these when setting a UIView’s autoresizingMask property. The autoresizing options are listed in the documentation as follows: enum { UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 << 0, UIViewAutoresizingFlexibleWidth = 1 << 1, UIViewAutoresizingFlexibleRightMargin = 1 << 2, UIViewAutoresizingFlexibleTopMargin = 1 << 3, UIViewAutoresizingFlexibleHeight = 1 << 4, UIViewAutoresizingFlexibleBottomMargin = 1 << 5 }; typedef NSUInteger UIViewAutoresizing; The << symbol is the left shift operator; the right operand says how many bits to shift the left operand. So pretend that an NSUInteger is 8 bits (it isn’t, but let’s keep things simple and short). Then this enum means that the following name–value pairs are defined (using binary notation for the values): UIViewAutoresizingNone 00000000 UIViewAutoresizingFlexibleLeftMargin 00000001 UIViewAutoresizingFlexibleWidth 00000010 UIViewAutoresizingFlexibleRightMargin 00000100 UIViewAutoresizingFlexibleTopMargin 00001000 and so on. The reason for this bit-based representation is that these values can be combined into a single value (a bitmask) that you pass to set the autoresizingMask. All Cocoa has to do in order to understand your intentions is to look to see which bits in the value that you pass are set to 1. So, for example, 00001010 would mean that UIView- 14 | Chapter 1: Just Enough C
  • 38.
    AutoresizingFlexibleTopMargin and UIViewAutoresizingFlexibleWidthare true (and that the others, by implication, are all false). The question is how to form the value 00001010 in order to pass it. You could just do the math, figure out that binary 00001010 is decimal 10, and set the autoresizingMask property to 10, but that’s not what you’re supposed to do, and it’s not a very good idea, because it’s error-prone and makes your code incomprehensible. Instead, use the bitwise-or operator to combine the desired options: myView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth; This notation works because the bitwise-or operator combines its operands by setting in the result any bits that are set in either of the operands, so 00001000 | 00000010 is 00001010, which is just the value we’re trying to convey. Simple assignment (K&R 2.10) is by the equal sign. But there are also compound as- signment operators that combine assignment with some other operation. For example: height *= 2; // same as saying: height = height * 2; The ternary operator (?:) is a way of specifying one of two values depending on a condition (K&R 2.11). The scheme is as follows: (condition) ? exp1 : exp2 If the condition is true (see the next section for what that means), the expression exp1 is evaluated and the result is used; otherwise, the expression exp2 is evaluated and the result is used. For example, you might use the ternary operator while performing an assignment, using this schema: myVariable = (condition) ? exp1 : exp2; What gets assigned to myVariable depends on the truth value of the condition. There’s nothing happening here that couldn’t be accomplished more verbosely with flow con- trol (see the next section), but the ternary operator can greatly improve clarity, and I use it a lot. Flow Control and Conditions Basic flow control is fairly simple and usually involves a condition in parentheses and a block of conditionally executed code in curly braces. These curly braces constitute a new scope, into which new variables can be introduced. So, for example: if (x == 7) { int i = 0; i += 1; } After the closing curly brace in the fourth line, the i introduced in the second line has ceased to exist, because its scope is the inside of the curly braces. If the contents of the curly braces consist of a single statement, the curly braces can be omitted, but I would Flow Control and Conditions | 15
  • 39.
    advise beginners againstthis shorthand, as you can confuse yourself. A common be- ginner mistake (which will be caught by the compiler) is forgetting the parentheses around the condition. The full set of flow control statements is given in K&R Chapter 3, and I’ll just summarize them schematically here (Example 1-1). Example 1-1. The C flow control constructs if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition) { statements; else if (condition) { statements; } else { statements; } while (condition) { statements; } do { statements; } while (condition); for (before-all; condition; after-each) { statements; } The if...else if...else structure can have as many else if blocks as needed, and the else block is optional. Instead of an extended if...else if...else if...else structure, when the conditions would consist of comparing various values against a single value, you can use the switch statement; however, I never use it, and I don’t recommend that you do either, as it is rather confusing and can easily go wrong. See K&R 3.4 if you’re interested. The C for loop needs some elaboration for beginners (Example 1-1). The before-all statement is executed once as the for loop is first encountered and is usually used for initialization of the counter. The condition is then tested, and if true, the block is exe- cuted; the condition is usually used to test whether the counter has reached its limit. The after-each statement is then executed, and is usually used to increment or decre- ment the counter; the condition is then immediately tested again. Thus, to execute a block using integer values 1, 2, 3, 4, and 5 for i, the notation is: 16 | Chapter 1: Just Enough C
  • 40.
    int i; for (i= 1; i < 6; i++) { // ... statements ... } The need for a counter intended to exist solely within the for loop is so common that C99 permits the declaration of the counter as part of the before-all statement; the declared variable’s scope is then inside the curly braces: for (int i = 1; i < 6; i++) { // ... statements ... } The for loop is one of the few areas in which Objective-C extends C’s flow-control syntax. Certain Objective-C objects represent enumerable collections of other objects; “enumerable” basically means that you can cycle through the collection, and cycling through a collection is called enumerating the collection. To make enumerating easy, Objective-C provides a for...in operator, which works like a for loop: SomeType* oneItem; for (oneItem in myCollection) { // ... statements .... } On each pass through the loop, the variable oneItem (or whatever you call it) takes on the next value from within the collection. As with the C99 for loop, oneItem can be declared in the for statement, limiting its scope to the curly braces: for (SomeType* oneItem in myCollection) { // ... statements .... } To abort a loop from inside the curly braces, use the break statement. To abort the current iteration from within the curly braces and proceed to the next iteration, use the continue statement. In the case of while and do, continue means to perform immediately the conditional test; in the case of a for loop, continue means to perform immediately the after-each statement and then the conditional test. C also has a goto statement that allows you to jump to a named (labeled) line in your code (K&R 3.8); even though goto is notoriously “considered harmful,” there are sit- uations in which it is pretty much necessary, especially because C’s flow control is otherwise so primitive. It is permissible for a C statement to be compounded of multiple state- ments, separated by commas, to be executed sequentially. The last of the multiple statements is the value of the compound statement as a whole. This construct, for instance, lets you perform some secondary action before each test of a condition or perform more than one after-each action (an example appears in Chapter 17). Flow Control and Conditions | 17
  • 41.
    We can nowturn to the question of what a condition consists of. C has no separate boolean type; a condition either evaluates to 0, in which case it is considered false, or it doesn’t, in which case it is true. Comparisons are performed using the equality and relational operators (K&R 2.6); for example, == compares for equality, and < compares for whether the first operand is less than the second. Logical expressions can be com- bined using the logical-and operator (&&) and the logical-or operator (||); using these along with parentheses and the not operator (!) you can form complex conditions. Evaluation of logical-and and logical-or expressions is short-circuited, meaning that if the left condition settles the question, the right condition is never even evaluated. Don’t confuse the logical-and operator (&&) and the logical-or operator (||) with the bitwise-and operator (&) and the bitwise-or operator (|) discussed earlier. Writing & when you mean && (or vice versa) can result in surprising behavior. The operator for testing basic equality, ==, is not a simple equal sign; forgetting the difference is a common novice mistake. The problem is that such code is legal: simple assignment, which is what the equal sign means, has a value, and any value is legal in a condition. So consider this piece of (nonsense) code: int i = 0; while (i = 1) { i = 0; } You might think that the while condition tests whether i is 1. You might then think: i is 0, so the while body will never be performed. Right? Wrong. The while condition does not test whether i is 1; it assigns 1 to i. The value of that assignment is also 1, so the condition evaluates to 1, which means true. So the while body is performed. More- over, even though the while body assigns 0 to i, the condition is then evaluated again and assigns 1 to i a second time, which means true yet again. And so on, forever; we’ve written an endless loop, and the program will hang. (And, depending on what compiler and settings you’re using, you might not even get a warning of trouble ahead.) C programmers actually revel in the fact that testing for zero and testing for false are the same thing and use it to create compact conditional expressions, which are con- sidered elegant and idiomatic. I don’t recommend that you make use of such idioms, as they can be confusing, but I must admit that even I do occasionally resort to this sort of thing: NSString* s = nil; // ... if (s) { // ... } The idea of that code is to test whether the NSString object s, between the time it was declared and the start of the if-block, has been set to an actual string. Because nil is a 18 | Chapter 1: Just Enough C
  • 44.
    You’re allowed tosay that, but it doesn’t seem to serve much purpose. On the other hand, the point of a function might be not so much the value it returns as other things it does as it is executing, so then it might make perfect sense to ignore its result. The parentheses in a function’s syntax are crucial. Parentheses are how C knows there’s a function. Parentheses after the function name in the function definition are how C knows this is a function definition, and they are needed even if this function takes no parameters. Parentheses after the function name in the function call are how C knows this is a function call, and they are needed even if this function call supplies no argu- ments. Using the bare name of a function is possible, because the name is effectively a kind of variable (and I’ll talk later about why you might want to do that), but it doesn’t call the function. Let’s return to the simple C function definition and call that I used as my example earlier. Suppose we combine that function definition and the call to that function into a single program: int square(int i) { return i * i; } int i = square(3); That is a legal program, but only because the definition of the square function precedes the call to that function. If we wanted to place the definition of the square function elsewhere, such as after the call to it, we would need at least to precede the call with a declaration of the square function (Example 1-2). The declaration looks just like the first line of the definition, but it is a statement, ending with a semicolon, rather than a left curly brace. Example 1-2. Declaring, calling, and defining a function int square(int i); int i = square(3); int square(int i) { return i * i; } The parameter names in the declaration do not have to match the parameter names in the definition, but all the types (and, of course, the name of the function) must match. The types constitute the signature of this function. In other words, it does not matter if the first line, the declaration, is rewritten thus: int square(int j); What does matter is that, both in the declaration and in the definition, square is a function taking one int parameter and returning an int. In Objective-C, when you’re sending a message to an object (Chapter 2), you won’t use a function call; you’ll use a method call (Chapter 3). But you will most definitely use plenty of C function calls as well. For example, earlier we initialized a CGPoint by setting its x element and its y element and by assigning its elements values in curly Functions | 21
  • 45.
    braces. But whatyou’ll usually do to make a new CGPoint is to call CGPointMake, which is declared like this: CGPoint CGPointMake ( CGFloat x, CGFloat y ); Despite its multiple lines and its indentations, this is indeed a C function declaration, just like the declaration for our simple square function. It says that CGPointMake is a C function that takes two CGFloat parameters and returns a CGPoint. So now you know (I hope) that it would be legal (and typical) to write this sort of thing: CGPoint myPoint = CGPointMake(4.3, 7.1); Pointer Parameters and the Address Operator I’ve mentioned several times that your variables referring to Objective-C objects are going to be pointers: NSString* s = @"Hello, world!"; Although it is common to speak loosely of s as an NSString (or just as a string), it is actually an NSString* — a pointer to an NSString. Therefore, when a C function or an Objective-C method expects an NSString* parameter, there’s no problem, because that’s exactly what you’ve got. For example, one way to concatenate two NSStrings is to call the NSString method stringByAppendingString: (that’s not a misprint; the colon is part of the name), which the documentation tells you is declared as follows: - (NSString *)stringByAppendingString:(NSString *)aString The space between the class name and the asterisk is optional, so this declaration is telling you (after you allow for the Objective-C syntax) that this method expects one NSString* parameter and returns an NSString*. That’s splendid because those kinds of pointers are just what you’ve got and just what you want. So this code would be legal: NSString* s1 = @"Hello, "; NSString* s2 = @"World!" NSString* s3 = [s1 stringByAppendingString: s2]; The idea, then, is that although Objective-C is chock-a-block with pointers and aster- isks, they don’t make things more complicated, as long as you remember that they are pointers. Sometimes, however, a function expects as a parameter a pointer to something, but what you’ve got is not a pointer but the thing itself. Thus, you need a way to create a pointer to that thing. The solution is the address operator (K&R 5.1), which is an ampersand before the name of the thing. For example, there’s an NSString method for reading from a file into an NSString, which is declared like this: 22 | Chapter 1: Just Enough C
  • 46.
    + (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError**)error Now, never mind what an id is, and don’t worry about the Objective-C method dec- laration syntax. Just consider the types of the parameters. The first one is an NSString*; that’s no problem, as every reference to an NSString is actually a pointer to an NSString. An NSStringEncoding turns out to be merely an alias to a primitive data type, an NSUInteger, so that’s no problem either. But what on earth is an NSError**? By all logic, it looks like an NSError** should be a pointer to a pointer to an NSError. And that’s exactly what it is. This method is asking to be passed a pointer to a pointer to an NSError. Well, it’s easy to declare a pointer to an NSError: NSError* myError; But how can we obtain a pointer to that? With the address operator! So our code might look, schematically, like this: NSString* myPath = // something or other; NSStringEncoding myEnc = // something or other; NSError* myError = nil; NSString* result = [NSString stringWithContentsOfFile: myPath encoding: myEnc error: &myError]; The important thing to notice is the ampersand. Because myError is a pointer to an NSError, &myError is a pointer to a pointer to an NSError, which is just what we’re expected to provide. Thus, everything goes swimmingly. This device lets Cocoa effectively return two results from this method call. It returns a real result, which we have captured by assigning it to the NSString pointer we’re calling result. But if there’s an error, it also wants to set the value of another object, an NSError object; the idea is that you can then study that NSError object to find out what went wrong. (Perhaps the file wasn’t where you said it was, or it wasn’t stored in the encoding youclaimeditwas.)BypassingapointertoapointertoanNSError,yougivethemethod free rein to do that. Before the call to stringWithContentsOfFile:, myError was unini- tialized; during the call to stringWithContentsOfFile:, Cocoa can, if it likes, repoint the pointer, thus giving myError an actual value. So the idea is that you first check result to see whether it’s nil. If it isn’t, fine; it’s the string you asked for. If it is, you then study the NSError that myError is now pointing to, to learn what went wrong. This pattern is frequently used in Cocoa. You can use the address operator to create a pointer to any named variable. A C function is technically a kind of named variable, so you can even create a pointer to a function! This is an example of when you’d use the name of the function without the parentheses: you aren’t calling the function, you’re talking about it. For example, &square is a pointer to the square function. In Chapter 9, I describe a situation in which this is a useful thing to do. Pointer Parameters and the Address Operator | 23
  • 47.
    Another operator usedin connection with pointers, or when memory must be allocated dynamically, is sizeof. It may be followed by a type name in parentheses or by a variable name; a variable name needn’t be in parentheses, but it can be, so most programmers ignore the distinction and use parentheses routinely, as if sizeof were a function. For example, the documentation shows the declaration for AudioSessionSetProperty like this: OSStatus AudioSessionSetProperty ( AudioSessionPropertyID inID, UInt32 inDataSize, const void *inData ); Never mind what an AudioSessionPropertyID is; it’s merely a value that you obtain and pass on. UInt32 is one of those derived numeric types I mentioned earlier. The discussion has already dealt with pointer-to-void and how to derive a pointer using the address operator. But look at the name of the second parameter; the function is asking for the size of the thing pointed to by the third parameter. Here’s an actual call to this function (from Chapter 27): UInt32 ambi = kAudioSessionCategory_AmbientSound; AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(ambi), &ambi); Files The little dance of declaring a function before calling it (Example 1-2) may seem rather absurd, but it is of tremendous importance in the C language, because it is what allows a C program to be arbitrarily large and complex. As your program grows, you can divide and organize it into multiple files. This kind of organization can make a large program much more maintainable — easier to read, easier to understand, easier to change without accidentally breaking things. A large C program therefore usually consists of two kinds of file: code files, whose filename ex- tension is .c, and header files, whose filename extension is .h. The build system will automatically “see” all the files and will know that together they constitute a single program, but there is also a rule in C that code inside one file cannot “see” another file unless it is explicitly told to do so. Thus, a file itself constitutes a scope; this is a delib- erate and valuable feature of C, because it helps you keep things nicely pigeonholed. The way you tell a C file to “see” another file is with the #include directive. The hash sign in the term #include is a signal that this line is an instruction to the preproces- sor. In this case, the word #include is followed by the name of another file, and the directive means that the preprocessor should simply replace the directive by the entire contents of the file that’s named. So the strategy for constructing a large C program is something like this: 24 | Chapter 1: Just Enough C
  • 48.
    • In each.c file, put the code that only this file needs to know about; typically, each file’s code consists of related functionality. • In each .h file, put the function declarations that multiple .c files might need to know about. • Have each .c file include those .h files containing the declarations it needs to know about. So, for example, if function1 is defined in file1.c, but file2.c might need to call function1, the declaration for function1 can go in file1.h. Now file1.c can include file1.h, so all of its functions, regardless of order, can call function1, and file2.c can also include file1.h, so all of its functions can call function1 (Figure 1-2). In short, header files are a way of letting code files share knowledge about one another without actually sharing code (because, if they did share code, that would violate the entire point of keeping the code in separate files). But how does the compiler know where, among all these multiple .c files, to begin execution? Every real C program contains, somewhere, exactly one function called main, and this is always the entry point for the program as a whole: the compiler sets things up so that when the program executes, main is called. The organization for large C programs that I’ve just described will also be, in effect, the organization for your iOS programs. (The chief difference will be that instead of .c files, you’ll use .m files, because .m is the conventional filename extension for telling Xcode that your files are written in Objective-C, not pure C.) Moreover, if you look at any iOS Xcode project, you’ll discover that it contains a file called main.m; and if you look at that file, you’ll find that it contains a function called main. That’s the entry point to your application’s code when it runs. Figure 1-2. How a large C program is divided into files Files | 25
  • 49.
    Furthermore, your iOSprograms consist not only of your code files and their corre- sponding .h files, but also of Apple’s code files and their corresponding .h files. The difference is that Apple’s code files (which are what constitutes Cocoa) have already been compiled. But your code must still #include Apple’s .h files so as to be able to see Apple’s declarations. If you look at an iOS Xcode project, you’ll find that any .h files it contains by default, as well as its main.m file, contain a line of this form: #import <UIKit/UIKit.h> That line is essentially a single massive #include that copies into your program the declarations for the entire basic iOS API. Moreover, each of your .m files #imports its corresponding .h file, including whatever the .h file #imports. Thus, all your code files include the basic iOS declarations. For example, earlier I said that CGPoint was defined like this: struct CGPoint { CGFloat x; CGFloat y; }; typedef struct CGPoint CGPoint; After the preprocessor operates on all your files, your .m files actually contain that definition of CGPoint. (In Xcode 3.2.x, you can even choose Build → Preprocess to confirm that this is true.) And that is why your code is able to use a CGPoint! The #import preprocessor directive is not mentioned in K&R. It’s an Objective-C ad- dition to the language. It’s based on #include, but it is used instead of #include because it (#import) contains some logic for making sure that the same material is not included more than once. Such repeated inclusion is a danger whenever there are many cross- dependent header files; use of #import solves the problem neatly. The #import directive, like the #include directive (K&R 4.11), can specify a file in angle brackets or in quotation marks: #import <UIKit/UIKit.h> #import "MyHeader.h" The quotation marks form means “look for the named file in the same folder as this file” (the .m file in which the #import line occurs). The angle brackets form means to look among the various header search paths supplied in the build settings; these search paths are set for you automatically, and you normally won’t need to modify them. In general, the distinction means that you’ll use angle brackets to refer to a header file owned by the Cocoa API and quotation marks to refer to a header file that you wrote. If you’re curious as to what an #import directive imports, select it (in Xcode) and choose File → Open Quickly to display the contents of the designated header file. 26 | Chapter 1: Just Enough C
  • 50.
    The Standard Library Youalso have at your disposal a large collection of built-in C library files. A library file is a centrally located collection of C functions, along with a .h file that you can include in order to make those functions available to your code. For example, suppose you want to round a float up to the next highest integer. The way to do this is to call some variety of the ceil function. You can read the ceil man page in Xcode, or by typing man ceil in the Terminal. The documentation tells you what #include to use to incorporate the correct header and also shows you the function declarations and tells you what those functions do. A small pure C program might thus look like this: #include <math.h> float f = 4.5; int i = ceilf(f); // now i is 5 In your iOS programs, math.h is included for you as part of the massive UIKit #import, so there’s no need to include it again. But some library functions might require an explicit #import. The standard library is discussed in K&R Appendix B. But the modern standard library has evolved since K&R; it is a superset of K&R’s library. Theceil function, for example, is listed in K&R appendix B, but the ceilf function is not. Similarly, if you wanted to generate a random number (which is likely if you’re writing a game program that needs to incorporate some unpredictable behavior), you probably wouldn’t use the rand function listed in K&R; you’d use the random function, which supersedes it. Forgetting that Objective-C is C and that the C library functions are available to your code is a common beginner mistake. More Preprocessor Directives Of the many other available preprocessor directives, the one you’ll use most often is #define. It is followed by a name and a value; at preprocess time, the value is substituted for the name down through this code file. As K&R very well explain (K&R 1.4), this is a good way to prevent “magic numbers” from being hidden and hard-coded into your program in a way that makes the program difficult to understand and maintain. For example, in an iOS app that lays out some text fields vertically, I might want them all to have the same space between them. Let’s say this space is 3.0. I shouldn’t write 3.0 repeatedly throughout my code as I calculate the layout; instead, I write: #define MIDSPACE 3.0 Now instead of the “magic number” 3.0, my code uses a meaningful name, MIDSPACE; at preprocessor time, the text MIDSPACE is replaced with the text 3.0. So it amounts to More Preprocessor Directives | 27
  • 51.
    the same thing,but if I decide to change this value and try a different one, all I have to do change is the #define line, not every occurrence of the number 3.0. A #define simply performs text substitution, so any expression can be used as the value. Sometimes you’ll want that expression to be an NSString literal. In Cocoa, NSString literals can be used as a key to a dictionary or the name of a notification. (Never mind for now what a dictionary or a notification is.) This situation is an invitation to error. If you have a dictionary containing a key @"mykey" and you mistype this elsewhere in your code as @"myKey" or @"mikey", the compiler won’t complain, but your program will misbehave. The solution is to define a name for this literal string: #define MYKEY @"mykey" Now use MYKEY throughout your code instead of @"mykey", and if you mistype MYKEY the preprocess substitution won’t be performed and the compiler will complain, catching the mistake for you. The #define directive can also be used to create a macro (K&R 4.11.2), a more elaborate form of text substitution. You’ll encounter a few Cocoa macros in the course of this book, but they will appear indistinguishable from functions; their secret identity as macros won’t concern you. There is also a #pragma mark directive that’s useful with Xcode; I talk about it when discussing the Xcode programming environment (Chapter 9). Data Type Qualifiers A variable’s data type can be declared with a qualifier before the name of the type, modifying something about how that variable is to be used. For example, the declara- tion can be preceded by the term const, which means (K&R 2.4) that it is illegal to change the variable’s value; the variable must be initialized in the same line as the declaration, and that’s the only value it can ever have. You can use a const variable as an alternative way (instead of #define) to prevent “magic numbers” and similar expressions. For example: const NSString* MYKEY = @"Howdy"; The Cocoa API itself makes heavy use of this device. For example, in some circum- stances Cocoa will pass a dictionary of information to your code. The documentation tells you what keys this dictionary contains. But instead of telling you a key as a string, the documentation tells you the key as a const NSString variable name: UIKIT_EXTERN NSString *const UIApplicationStatusBarOrientationUserInfoKey; (Never mind what UIKIT_EXTERN means.) This declaration tells you that UIApplication- StatusBarOrientationUserInfoKey is the name of an NSString, and you are to trust that its value is set for you. You are to go ahead and use this name whenever you want to speak of this particular key, secure in the knowledge that the actual key name string 28 | Chapter 1: Just Enough C
  • 52.
    will be substituted.You do not have to know what that actual key name string is. In this way, if you make a mistake in typing the variable name, the compiler will catch the mistake because you’ll be using the name of an undefined variable. Another commonly used qualifier is static. This term is unfortunately used in two rather different ways in C; the way I commonly use it is inside a function. Inside a function, static indicates that the memory set aside for a variable should not be re- leased after the function returns; rather, the variable remains and maintains its value for the next time the function is called. A static variable is useful, for example, when you want to call a function many times without the overhead of calculating the result each time (after the first time). First test to see whether the static value has already been calculated: if it hasn’t, this must be the first time the function is being called, so you calculate it; if it has, you just return it. Here’s a schematic version: int myfunction() { static int result = 0; // 0 means we haven't done the calculation yet if (result == 0) { // calculate result and set it } return result; } A very common use of a static variable in Objective-C is to implement a singleton instance returned by a class factory method. If that sounds complicated, don’t worry; it isn’t. Here’s an example from my own code, which you can grasp even though we haven’t discussed Objective-C yet: + (CardPainter*) sharedPainter { static CardPainter* sp = nil; if (nil == sp) sp = [[CardPainter alloc] init]; return sp; } That code says: If the CardPainter instance sp has never been created, create it, and in any case, now return it. Thus, no matter how many times this method is called, the instance will be created just once and that same instance will be returned every time. Data Type Qualifiers | 29
  • 54.
    CHAPTER 2 Object-Based Programming Myobject all sublime. —W. S. Gilbert, The Mikado Objective-C, the native language for programming the Cocoa API, is an object-oriented language; in order to use it, the programmer must have an appreciation of the nature of objects and object-based programming. There’s little point in learning the syntax of Objective-C message sending or instantiation without a clear understanding of what a message or an instance is. That is what this chapter is about. Objects An object, in programming, is based on the concept of an object in the real world. It’s an independent, self-contained thing. These objects, unlike purely inert objects in the real world, have abilities. So an object in programming is more like a clock than a rock; it doesn’t just sit there, but actually does something. Perhaps one could compare an object in programming more to the animate objects of the real world, as opposed to the inanimate objects, except that — unlike real-world animate things — a program- ming object is supposed to be predictable: in particular, it does what you tell it. In the real world, you tell a dog to sit and anything can happen; in the programming world, you tell a dog to sit and it sits. (This is why so many of us prefer programming to dealing with the real world.) In object-based programming, a program is organized into many discrete objects. This organization can make life much easier for the programmer. Each object has abilities that are specialized for that object. You can think of this as being a little like how an automobile assembly line works. Each worker or station along the line does one thing (screw on the bumpers, or paint the door, or whatever) and does it well. You can see immediately how this organization helps the programmer. If the car is coming off the assembly line with the door badly painted, it is very likely that the blame lies with the door-painting object, so we know where to look for the bug in our code. Or, if we decide 31
  • 55.
    Exploring the Varietyof Random Documents with Different Content
  • 57.
    Fig. 94. § 13.Fig. 94, page 171, will serve to show the mode in which similar arrangements are carried into the smallest detail. It is magnified four times from a cluster of leaves in the foreground of the “Isis” (Liber Studiorum). Figs. 95 and 96, page 172, show the arrangement of the two groups composing it; the lower is purely symmetrical, with trefoiled centre and broad masses for wings; the uppermost is a sweeping continuous curve, symmetrical, but foreshortened. Both are clasped by arrow-shaped leaves. The two whole groups themselves are, in turn, members of another larger group, composing the entire foreground, and consisting of broad dock-leaves, with minor clusters on the right and left, of which these form the chief portion on the right side. Fig. 95.
  • 58.
    Fig. 96. § 14.Unless every leaf, and every visible point or object, however small, forms a part of some harmony of this kind (these symmetrical conditions being only the most simple and obvious), it has no business in the picture. It is the necessary connection of all the forms and colors, down to the last touch, which constitutes great or inventive work, separated from all common work by an impassable gulf. By diligently copying the etchings of the Liber Studiorum, the reader may, however, easily attain the perception of the existence of these relations, and be prepared to understand Turner’s more elaborate composition. It would take many figures to disentangle and explain the arrangements merely of the leaf cluster, Fig. 78, facing page 97; but that there is a system, and that every leaf has a fixed value and place in it, can hardly but be felt at a glance. It is curious that, in spite of all the constant talkings of “composition” which goes on among art students, true composition is just the last thing which appears to be perceived. One would have thought that in this
  • 59.
    group, at least,the value of the central black leaf would have been seen, of which the principal function is to point towards, and continue, the line of bank above. See Plate 62. But a glance at the published Plate in the England series will show that no idea of the composition had occurred to the engraver’s mind. He thought any leaves would do, and supplied them from his own repertory of hack vegetation. § 15. I would willingly enlarge farther on this subject—it is a favorite one with me; but the figures required for any exhaustive treatment of it would form a separate volume. All that I can do is to indicate, as these examples do sufficiently, the vast field open to the student’s analysis if he cares to pursue the subject; and to mark for the general reader these two strong conclusions:—that nothing in great work is ever either fortuitous or contentious. It is not fortuitous; that is to say, not left to fortune. The “must do it by a kind of felicity” of Bacon is true; it is true also that an accident is often suggestive to an inventor. Turner himself said, “I never lose an accident.” But it is this not losing it, this taking things out of the hands of Fortune, and putting them into those of force and foresight, which attest the master. Chance may sometimes help, and sometimes provoke, a success; but must never rule, and rarely allure. And, lastly, nothing must be contentious. Art has many uses and many pleasantnesses; but of all its services, none are higher than its setting forth, by a visible and enduring image, the nature of all true authority and freedom; Authority which defines and directs the action of benevolent law; and Freedom which consists in deep and soft consent of individual4 helpfulness. 1 The sails in the engraving were put in to catch the public eye. There are none in the drawing. 2 These etchings of compositions are all reversed, for they are merely sketches on the steel, and I cannot sketch easily except straight from the
  • 60.
    drawing, and withoutreversing. The looking-glass plagues me with cross lights. As examples of composition, it does not the least matter which way they are turned; and the reader may see this Schaffhausen subject from the right side of the Rhine, by holding the book before a glass. The rude indications of the figures in the Loire subject are nearly facsimiles of Turner’s. 3 With the exception of the jagged ledge rising out of the foam below which comes from the north side, and is admirable in its expression of the position of the limestone-beds, which, rising from below the drift gravel of Constance, are the real cause of the fall of Schaffhausen. 4 “Individual,” that is to say, distinct and separate in character, though joined in purpose. I might have enlarged on this head, but that all I should care to say has been already said admirably by Mr. J. S. Mill in his essay on Liberty. CHAPTER III. THE RULE OF THE GREATEST. § 1. In the entire range of art principles, none perhaps present a difficulty so great to the student, or require from the teacher expression so cautious, and yet so strong, as those which concern the nature and influence of magnitude. In one sense, and that deep, there is no such thing as magnitude. The least thing is as the greatest, and one day as a thousand years, in the
  • 61.
    eyes of theMaker of great and small things. In another sense, and that close to us and necessary, there exist both magnitude and value. Though not a sparrow falls to the ground unnoted, there are yet creatures who are of more value than many; and the same Spirit which weighs the dust of the earth in a balance, counts the isles as a little thing. § 2. The just temper of human mind in this matter may, nevertheless, be told shortly. Greatness can only be rightly estimated when minuteness is justly reverenced. Greatness is the aggregation of minuteness; nor can its sublimity be felt truthfully by any mind unaccustomed to the affectionate watching of what is least. But if this affection for the least be unaccompanied by the powers of comparison and reflection; if it be intemperate in its thirst, restless in curiosity, and incapable of the patient and self-commandant pause which is wise to arrange, and submissive to refuse, it will close the paths of noble art to the student as effectually, and hopelessly, as even the blindness of pride, or impatience of ambition. § 3. I say the paths of noble art, not of useful art. All accurate investigation will have its reward; the morbid curiosity will at least slake the thirst of others, if not its own; and the diffused and petty affections will distribute, in serviceable measure, their minute delights and narrow discoveries. The opposite error, the desire of greatness as such, or rather of what appears great to indolence and vanity;—the instinct which I have described in the “Seven Lamps,” noting it, among the Renaissance builders, to be an especial and unfailing sign of baseness of mind, is as fruitless as it is vile; no way profitable—every way harmful: the widest and most corrupting expression of vulgarity. The microscopic drawing of an insect may be precious; but nothing except disgrace and misguidance will ever be gathered from such work as that of Haydon or Barry. § 4. The work I have mostly had to do, since this essay was begun, has been that of contention against such debased issues of swollen insolence
  • 62.
    and windy conceit;but I have noticed lately, that some lightly-budding philosophers have depreciated true greatness; confusing the relations of scale, as they bear upon human instinct and morality; reasoning as if a mountain were no nobler than a grain of sand, or as if many souls were not of mightier interest than one. To whom it must be shortly answered that the Lord of power and life knew which were His noblest works, when He bade His servant watch the play of the Leviathan, rather than dissect the spawn of the minnow; and that when it comes to practical question whether a single soul is to be jeoparded for many, and this Leonidas, or Curtius, or Winkelried shall abolish—so far as abolishable—his own spirit, that he may save more numerous spirits, such question is to be solved by the simple human instinct respecting number and magnitude, not by reasonings on infinity:— “Le navigateur, qui, la nuit, voit l’océan étinceler de lumière, danser en guirlandes de feu, s’égaye d’abord de ce spectacle. Il fait dix lieues; la guirlande s’allonge indéfiniment, elle s’agite, se tord, se noue, aux mouvements de la lame; c’est un serpent monstrueux qui va toujours s’allongeant, jusqu’à trente lieues, quarante lieues. Et tout cela n’est qu’une danse d’animalcules imperceptibles. En quel nombre? A cette question l’imagination s’effraye; elle sent là une nature de puissance immense, de richesse epouvantable.... Que sont ces petits des petits? Rien moins que les constructeurs du globe où nous sommes. De leurs corps, de leurs débris, ils ont préparé le sol qui est sous nos pas.... Et ce sont les plus petits qui ont fait les plus grandes choses. L’imperceptible rhizopode s’est bâti un monument bien autre que les pyramides, pas moins que l’Italie centrale, une notable partie de la chaîne des Apennins. Mais c’était trop peu encore; les masses énormes du Chili, les prodigieuses Cordillères, qui regardent le monde à leurs pieds, sont le monument funéraire où cet être insaisissable, et pour ainsi dire, invisible, a enseveli les débris de son espèce dïsparue.”—(Michelet: L’Insecte.)
  • 63.
    § 5. Inthese passages, and those connected with them in the chapter from which they are taken, itself so vast in scope, and therefore so sublime, we may perhaps find the true relations of minuteness, multitude, and magnitude. We shall not feel that there is no such thing as littleness, or no such thing as magnitude. Nor shall we be disposed to confuse a Volvox with the Cordilleras; but we may learn that they both are bound together by links of eternal life and toil; we shall see the vastest thing noble, chiefly for what it includes; and the meanest for what it accomplishes. Thence we might gather—and the conclusion will be found in experience true—that the sense of largeness would be most grateful to minds capable of comprehending, balancing, and comparing; but capable also of great patience and expectation; while the sense of minute wonderfulness would be attractive to minds acted upon by sharp, small, penetrative sympathies, and apt to be impatient, irregular, and partial. This fact is curiously shown in the relations between the temper of the great composers and the modern pathetic school. I was surprised at the first rise of that school, now some years ago, by observing how they restrained themselves to subjects which in other hands would have been wholly uninteresting (compare Vol. IV., p. 19); and in their succeeding efforts, I saw with increasing wonder, that they were almost destitute of the power of feeling vastness, or enjoying the forms which expressed it. A mountain or great building only appeared to them as a piece of color of a certain shape. The powers it represented, or included, were invisible to them. In general they avoided subjects expressing space or mass, and fastened on confined, broken, and sharp forms; liking furze, fern, reeds, straw, stubble, dead leaves, and such like, better than strong stones, broad-flowing leaves, or rounded hills: in all such greater things, when forced to paint them, they missed the main and mighty lines; and this no less in what they loved than in what they disliked; for though fond of foliage, their trees always had a tendency to congeal into little acicular thorn-hedges, and never tossed free. Which modes of choice proceed naturally from a petulant sympathy with local and immediately visible interests or sorrows, not regarding their large consequences, nor capable
  • 64.
    of understanding moremassive view or more deeply deliberate mercifulness;—but peevish and horror-struck, and often incapable of self- control, though not of self-sacrifice. There are more people who can forget themselves than govern themselves. This narrowly pungent and bitter virtue has, however, its beautiful uses, and is of special value in the present day, when surface-work, shallow generalization, and cold arithmetical estimates of things, are among the chief dangers and causes of misery which men have to deal with. § 6. On the other hand, and in clear distinction from all such workers, it is to be remembered that the great composers, not less deep in feeling, are in the fixed habit of regarding as much the relations and positions, as the separate nature, of things; that they reap and thrash in the sheaf, never pluck ears to rub in the hand; fish with net, not line, and sweep their prey together within great cords of errorless curve;—that nothing ever bears to them a separate or isolated aspect, but leads or links a chain of aspects—that to them it is not merely the surface, nor the substance, of anything that is of import; but its circumference and continence: that they are pre-eminently patient and reserved; observant, not curious;—comprehensive, not conjectural; calm exceedingly; unerring, constant, terrible in steadfastness of intent; unconquerable: incomprehensible: always suggesting, implying, including, more than can be told. § 7. And this may be seen down to their treatment of the smallest things. For there is nothing so small but we may, as we choose, see it in the whole, or in part, and in subdued connection with other things, or in individual and petty prominence. The greatest treatment is always that which gives conception the widest range, and most harmonious guidance;—it being permitted us to employ a certain quantity of time,
  • 65.
    and certain numberof touches of pencil—he who with these embraces the largest sphere of thought, and suggests within that sphere the most perfect order of thought, has wrought the most wisely, and therefore most nobly. § 8. I do not, however, purpose here to examine or illustrate the nature of great treatment—to do so effectually would need many examples from the figure composers; and it will be better (if I have time to work out the subject carefully) that I should do so in a form which may be easily accessible to young students. Here I will only state in conclusion what it is chiefly important for all students to be convinced of, that all the technical qualities by which greatness of treatment is known, such as reserve in color, tranquillity and largeness of line, and refusal of unnecessary objects of interest, are, when they are real, the exponents of an habitually noble temper of mind, never the observances of a precept supposed to be useful. The refusal or reserve of a mighty painter cannot be imitated; it is only by reaching the same intellectual strength that you will be able to give an equal dignity to your self-denial. No one can tell you beforehand what to accept, or what to ignore; only remember always, in painting as in eloquence, the greater your strength, the quieter will be your manner, and the fewer your words; and in painting, as in all the arts and acts of life, the secret of high success will be found, not in a fretful, and various excellence, but in a quiet singleness of justly chosen aim.
  • 66.
    CHAPTER IV. THE LAWOF PERFECTNESS. §1. Among the several characteristics of great treatment which in the last chapter were alluded to without being enlarged upon, one will be found several times named;—reserve. It is necessary for our present purpose that we should understand this quality more distinctly. I mean by it the power which a great painter exercises over himself in fixing certain limits, either of force, of color, or of quantity of work;—limits which he will not transgress in any part of his picture, even though here and there a painful sense of incompletion may exist, under the fixed conditions, and might tempt an inferior workman to infringe them. The nature of this reserve we must understand in order that we may also determine the nature of true completion or perfectness, which is the end of composition. § 2. For perfectness, properly so called, means harmony. The word signifies, literally, the doing our work thoroughly. It does not mean carrying it up to any constant and established degree of finish, but carrying the whole of it up to a degree determined upon. In a chalk or pencil sketch by a great master, it will often be found that the deepest shades are feeble tints of pale gray; the outlines nearly invisible, and the forms brought out by a ghostly delicacy of touch, which, on looking close to the paper, will be indistinguishable from its general texture. A single line of ink, occurring anywhere in such a drawing, would of course destroy it; placed in the darkness of a mouth or nostril, it would turn the expression into a caricature; on a cheek or brow it would be simply a blot. Yet let the blot remain, and let the master work up to it with lines of similar force; and the drawing which was before perfect, in terms of
  • 67.
    pencil, will become,under his hand, perfect in terms of ink; and what was before a scratch on the cheek will become a necessary and beautiful part of its gradation. All great work is thus reduced under certain conditions, and its right to be called complete depends on its fulfilment of them, not on the nature of the conditions chosen. Habitually, indeed, we call a colored work which is satisfactory to us, finished, and a chalk drawing unfinished; but in the mind of the master, all his work is, according to the sense in which you use the word, equally perfect or imperfect. Perfect, if you regard its purpose and limitation; imperfect, if you compare it with the natural standard. In what appears to you consummate, the master has assigned to himself terms of shortcoming, and marked with a sad severity the point up to which he will permit himself to contend with nature. Were it not for his acceptance of such restraint, he could neither quit his work, nor endure it. He could not quit it, for he would always perceive more that might be done; he could not endure it, because all doing ended only in more elaborate deficiency. § 3. But we are apt to forget, in modern days, that the reserve of a man who is not putting forth half his strength is different in manner and dignity from the effort of one who can do no more. Charmed, and justly charmed, by the harmonious sketches of great painters, and by the grandeur of their acquiescence in the point of pause, we have put ourselves to produce sketches as an end instead of a means, and thought to imitate the painter’s scornful restraint of his own power, by a scornful rejection of the things beyond ours. For many reasons, therefore, it becomes desirable to understand precisely and finally what a good painter means by completion. § 4. The sketches of true painters may be classed under the following heads:—
  • 68.
    I. Experimental.—In whichthey are assisting an imperfect conception of a subject by trying the look of it on paper in different ways. By the greatest men this kind of sketch is hardly ever made; they conceive their subjects distinctly at once, and their sketch is not to try them, but to fasten them down. Raphael’s form the only important exception—and the numerous examples of experimental work by him are evidence of his composition being technical rather than imaginative. I have never seen a drawing of the kind by any great Venetian. Among the nineteen thousand sketches by Turner—which I arranged in the National Gallery—there was, to the best of my recollection, not one. In several instances the work, after being carried forward a certain length, had been abandoned and begun again with another view; sometimes also two or more modes of treatment had been set side by side with a view to choice. But there were always two distinct imaginations contending for realization—not experimental modifications of one. § 5. II. Determinant.—The fastening down of an idea in the simplest terms, in order that it may not be disturbed or confused by after work. Nearly all the great composers do this, methodically, before beginning a painting. Such sketches are usually in a high degree resolute and compressive; the best of them outlined or marked calmly with the pen, and deliberately washed with color, indicating the places of the principal lights. Fine drawings of this class never show any hurry or confusion. They are the expression of concluded operations of mind, are drawn slowly, and are not so much sketches, as maps. § 6. III. Commemorative.—Containing records of facts which the master required. These in their most elaborate form are “studies,” or drawings, from Nature, of parts needed in the composition, often highly finished in the part which is to be introduced. In this form, however, they never occur by the greatest imaginative masters. For by a truly great
  • 69.
    inventor everything isinvented; no atom of the work is unmodified by his mind; and no study from nature, however beautiful, could be introduced by him into his design without change; it would not fit with the rest. Finished studies for introduction are therefore chiefly by Leonardo and Raphael, both technical designers rather than imaginative ones. Commemorative sketches, by great masters, are generally hasty, merely to put them in mind of motives of invention, or they are shorthand memoranda of things with which they do not care to trouble their memory; or, finally, accurate notes of things which they must not modify by invention, as local detail, costume, and such like. You may find perfectly accurate drawings of coats of arms, portions of dresses, pieces of architecture, and so on, by all the great men; but you will not find elaborate studies of bits of their pictures.
  • 70.
  • 71.
    § 7. Whenthe sketch is made merely as a memorandum, it is impossible to say how little, or what kind of drawing, may be sufficient for the purpose. It is of course likely to be hasty from its very nature, and unless the exact purpose be understood, it may be as unintelligible as a piece of shorthand writing. For instance, in the corner of a sheet of sketches made at sea, among those of Turner, at the National Gallery, occurs this one, Fig. 97. I suppose most persons would not see much use in it. It nevertheless was probably one of the most important sketches made in Turner’s life, fixing for ever in his mind certain facts respecting the sunrise from a clear sea-horizon. Having myself watched such sunrise, occasionally, I perceive this sketch to mean as follows:— (Half circle at the top.) When the sun was only half out of the sea, the horizon was sharply traced across its disk, and red streaks of vapor crossed the lower part of it. (Horseshoe underneath.) When the sun had risen so far as to show three-quarters of its diameter, its light became so great as to conceal the sea-horizon, consuming it away in descending rays. (Smaller horseshoe below.) When on the point of detaching itself from the horizon, the sun still consumed away the line of the sea, and looked as if pulled down by it. (Broken oval.) Having risen about a fourth of its diameter above the horizon, the sea-line reappeared; but the risen orb was flattened by refraction into an oval. (Broken circle.) Having risen a little farther above the sea-line, the sun, at last, got itself round, and all right, with sparkling reflection on the waves just below the sea-line. This memorandum is for its purpose entirely perfect and efficient, though the sun is not drawn carefully round, but with a dash of the pencil; but there is no affected or desired slightness. Could it have been
  • 72.
    drawn round asinstantaneously, it would have been. The purpose is throughout determined; there is no scrawling, as in vulgar sketching.1 § 8. Again, Fig. 98 is a facsimile of one of Turner’s “memoranda,” of a complete subject,2 Lausanne, from the road to Fribourg. To face page Fig. 98.
  • 73.
    This example isentirely characteristic of his usual drawings from nature, which unite two characters, being both commemorative and determinant:—Commemorative, in so far as they note certain facts about the place: determinant, in that they record an impression received from the place there and then, together with the principal arrangement of the composition in which it was afterwards to be recorded. In this mode of sketching, Turner differs from all other men whose work I have studied. He never draws accurately on the spot, with the intention of modifying or composing afterwards from the materials; but instantly modifies as he draws, placing his memoranda where they are to be ultimately used, and taking exactly what he wants, not a fragment or line more. § 9. This sketch has been made in the afternoon. He had been impressed as he walked up the hill, by the vanishing of the lake in the golden horizon, without end of waters, and by the opposition of the pinnacled castle and cathedral to its level breadth. That must be drawn! and from this spot, where all the buildings are set well together. But it lucklessly happens that, though the buildings come just where he wants them in situation, they don’t in height. For the castle (the square mass on the right) is in reality higher than the cathedral, and would block out the end of the lake. Down it goes instantly a hundred feet, that we may see the lake over it; without the smallest regard for the military position of Lausanne. § 10. Next: The last low spire on the left is in truth concealed behind the nearer bank, the town running far down the hill (and climbing another hill) in that direction. But the group oi spires, without it, would not be rich enough to give a proper impression of Lausanne, as a spiry place. Turner quietly sends to fetch the church from round the corner, places it where he likes, and indicates its distance only by aërial perspective (much greater in the pencil drawing than in the woodcut). § 11. But again: Not only the spire of the lower church, but the peak of the Rochers d’Enfer (that highest in the distance) would in reality be out
  • 74.
    of sight; itis much farther round to the left. This would never do either; for without it, we should have no idea that Lausanne was opposite the mountains, nor should we have a nice sloping line to lead us into the distance. With the same unblushing tranquillity of mind in which he had ordered up the church, Turner sends also to fetch the Rochers d’Enfer; and puts them also where he chooses, to crown the slope of distant hill, which, as every traveller knows, in its decline to the west, is one of the most notable features of the view from Lausanne. § 12. These modifications, easily traceable in the large features of the design, are carried out with equal audacity and precision in every part of it. Every one of those confused lines on the right indicates something that is really there, only everything is shifted and sorted into the exact places that Turner chose. The group of dark objects near us at the foot of the bank is a cluster of mills, which, when the picture was completed, were to be the blackest things in it, and to throw back the castle, and the golden horizon; while the rounded touches at the bottom, under the castle, indicate a row of trees, which follow a brook coming out of the ravine behind us; and were going to be made very round indeed in the picture (to oppose the spiky and angular masses of castle) and very consecutive, in order to form another conducting line into the distance. § 13. These motives, or motives like them, might perhaps be guessed on looking at the sketch. But no one without going to the spot would understand the meaning of the vertical lines in the left-hand lowest corner. They are a “memorandum” of the artificial verticalness of a low sandstone cliff, which has been cut down there to give space for a bit of garden belonging to a public-house beneath, from which garden a path leads along the ravine to the Lausanne rifle ground. The value of these vertical lines in repeating those of the cathedral is very great; it would be
  • 75.
    greater still inthe completed picture, increasing the sense of looking down from a height, and giving grasp of, and power over, the whole scene. § 14. Throughout the sketch, as in all that Turner made, the observing and combining intellect acts in the same manner. Not a line is lost, nor a moment of time; and though the pencil flies, and the whole thing is literally done as fast as a piece of shorthand writing, it is to the full as purposeful and compressed, so that while there are indeed dashes of the pencil which are unintentional, they are only unintentional as the form of a letter is, in fast writing, not from want of intention, but from the accident of haste. § 15. I know not if the reader can understand,—I myself cannot, though I see it to be demonstrable,—the simultaneous occurrence of idea which produces such a drawing as this: the grasp of the whole, from the laying of the first line, which induces continual modifications of all that is done, out of respect to parts not done yet. No line is ever changed or effaced: no experiment made; but every touch is placed with reference to all that are to succeed, as to all that have gone before; every addition takes its part, as the stones in an arch of a bridge; the last touch locks the arch. Remove that keystone, or remove any other of the stones of the vault, and the whole will fall. § 16. I repeat—the power of mind which accomplishes this, is yet wholly inexplicable to me, as it was when first I defined it in the chapter on imagination associative, in the second volume. But the grandeur of the power impresses me daily more and more; and, in quitting the subject of invention, let me assert finally, in clearest and strongest terms, that no painting is of any true imaginative perfectness at all, unless it has been thus conceived. One sign of its being thus conceived may be always found in the straightforwardness of its work. There are continual disputes among
  • 76.
    artists as tothe best way of doing things, which may nearly all be resolved into confessions of indetermination. If you know precisely what you want, you will not feel much hesitation in setting about it; and a picture may be painted almost any way, so only that it can be a straight way. Give a true painter a ground of black, white, scarlet, or green, and out of it he will bring what you choose. From the black, brightness; from the white, sadness; from the scarlet, coolness; from the green, glow: he will make anything out of anything, but in each case his method will be pure, direct, perfect, the shortest and simplest possible. You will find him, moreover, indifferent as to succession of process. Ask him to begin at the bottom of the picture instead of the top,—to finish two square inches of it without touching the rest, or to lay a separate ground for every part before finishing any;—it is all the same to him! What he will do if left to himself, depends on mechanical convenience, and on the time at his disposal. If he has a large brush in his hand, and plenty of one color ground, he may lay as much as is wanted of that color, at once, in every part of the picture where it is to occur; and if any is left, perhaps walk to another canvas, and lay the rest of it where it will be wanted on that. If, on the contrary, he has a small brush in his hand, and is interested in a particular spot of the picture, he will, perhaps, not stir from it till that bit is finished. But the absolutely best, or centrally, and entirely right way of painting is as follows:— § 17. A light ground, white, red, yellow, or gray, not brown, or black. On that an entirely accurate, and firm black outline of the whole picture, in its principal masses. The outline to be exquisitely correct as far as it reaches, but not to include small details; the use of it being to limit the masses of first color. The ground-colors then to be laid firmly, each on its own proper part of the picture, as inlaid work in a mosaic table, meeting each other truly at the edges: as much of each being laid as will get itself into the state which the artist requires it to be in for his second painting, by the time he comes to it. On this first color, the second colors and subordinate masses laid in due order, now, of course, necessarily without
  • 77.
    previous outline, andall small detail reserved to the last, the bracelet being not touched, nor indicated in the last, till the arm is finished.3 § 18. This is, as far as it can be expressed in few words, the right, or Venetian way of painting; but it is incapable of absolute definition, for it depends on the scale, the material, and the nature of the object represented, how much a great painter will do with his first color; or how many after processes he will use. Very often the first color, richly blended and worked into, is also the last; sometimes it wants a glaze only to modify it; sometimes an entirely different color above it. Turner’s storm- blues, for instance, were produced by a black ground, with opaque blue, mixed with white, struck over it.4 The amount of detail given in the first color will also depend on convenience. For instance, if a jewel fastens a fold of dress, a Venetian will lay probably a piece of the jewel color in its place at the time he draws the fold; but if the jewel falls upon the dress, he will paint the folds only in the ground color, and the jewel afterwards. For in the first case his hand must pause, at any rate, where the fold is fastened; so that he may as well mark the color of the gem: but he would have to check his hand in the sweep with which he drew the drapery, if he painted a jewel that fell upon it with the first color. So far, however, as he can possibly use the under color, he will, in whatever he has to superimpose. There is a pretty little instance of such economical work in the painting of the pearls on the breast of the elder princess, in our best Paul Veronese (Family of Darius). The lowest is about the size of a small hazel-nut, and falls on her rose-red dress. Any other but a Venetian would have put a complete piece of white paint over the dress, for the whole pearl, and painted into that the colors of the stone. But Veronese knows beforehand that all the dark side of the pearl will reflect the red of the dress. He will not put white over the red, only to put red over the white again. He leaves the actual dress for the dark side of the pearl, and with two small separate touches, one white, another brown, places its high light and shadow. This he does with perfect care and calm; but in two decisive seconds. There is no dash, nor display, nor hurry, nor error.
  • 78.
    The exactly rightthing is done in the exactly right place, and not one atom of color, nor moment of time spent vainly. Look close at the two touches,—you wonder what they mean. Retire six feet from the picture— the pearl is there! § 19. The degree in which the ground colors are extended over his picture, as he works, is to a great painter absolutely indifferent. It is all the same to him whether he grounds a head, and finishes it at once to the shoulders, leaving all round it white; or whether he grounds the whole picture. His harmony, paint as he will, never can be complete till the last touch is given; so long as it remains incomplete, he does not care how little of it is suggested, or how many notes are missing. All is wrong till all is right; and he must be able to bear the all-wrongness till his work is done, or he cannot paint at all. His mode of treatment will, therefore, depend on the nature of his subject; as is beautifully shown in the water- color sketches by Turner in the National Gallery. His general system was to complete inch by inch; leaving the paper quite white all round, especially if the work was to be delicate. The most exquisite drawings left unfinished in the collection—those at Rome and Naples—are thus outlined accurately on pure white paper, begun in the middle of the sheet, and worked out to the side, finishing as he proceeds. If, however, any united effect of light or color is to embrace a large part of the subject, he will lay it in with a broad wash over the whole paper at once; then paint into it using it as a ground, and modifying it in the pure Venetian manner. His oil pictures were laid roughly with ground colors, and painted into with such rapid skill, that the artists who used to see him finishing at the Academy sometimes suspected him of having the picture finished underneath the colors he showed, and removing, instead of adding, as they watched. § 20. But, whatever the means used may be, the certainty and directness of them imply absolute grasp of the whole subject, and without this grasp there is no good painting. This, finally, let me declare, without qualification—that partial conception is no conception. The whole
  • 79.
    picture must beimagined, or none of it is. And this grasp of the whole implies very strange and sublime qualities of mind. It is not possible, unless the feelings are completely under control; the least excitement or passion will disturb the measured equity of power; a painter needs to be as cool as a general; and as little moved or subdued by his sense of pleasure, as a soldier by the sense of pain. Nothing good can be done without intense feeling; but it must be feeling so crushed, that the work is set about with mechanical steadiness, absolutely untroubled, as a surgeon,—not without pity, but conquering it and putting it aside—begins an operation. Until the feelings can give strength enough to the will to enable it to conquer them, they are not strong enough. If you cannot leave your picture at any moment;—cannot turn from it and go on with another, while the color is drying;—cannot work at any part of it you choose with equal contentment—you have not firm enough grasp of it. § 21. It follows also, that no vain or selfish person can possibly paint, in the noble sense of the word. Vanity and selfishness are troublous, eager, anxious, petulant:—painting can only be done in calm of mind. Resolution is not enough to secure this; it must be secured by disposition as well. You may resolve to think of your picture only; but, if you have been fretted before beginning, no manly or clear grasp of it will be possible for you. No forced calm is calm enough. Only honest calm,— natural calm. You might as well try by external pressure to smoothe a lake till it could reflect the sky, as by violence of effort to secure the peace through which only you can reach imagination. That peace must come in its own time; as the waters settle themselves into clearness as well as quietness; you can no more filter your mind into purity than you can compress it into calmness; you must keep it pure, if you would have it pure; and throw no stones into it, if you would have it quiet. Great courage and self-command may, to a certain extent, give power of painting without the true calmness underneath; but never of doing first- rate work. There is sufficient evidence of this, in even what we know of great men, though of the greatest, we nearly always know the least (and
  • 80.
    that necessarily; theybeing very silent, and not much given to setting themselves forth to questioners; apt to be contemptuously reserved, no less than unselfishly). But in such writings and sayings as we possess of theirs, we may trace a quite curious gentleness and serene courtesy. Rubens’ letters are almost ludicrous in their unhurried politeness. Reynolds, swiftest of painters, was gentlest of companions; so also Velasquez, Titian, and Veronese. § 22. It is gratuitous to add that no shallow or petty person can paint. Mere cleverness or special gift never made an artist. It is only perfectness of mind, unity, depth, decision, the highest qualities, in fine, of the intellect, which will form the imagination. § 23. And, lastly, no false person can paint. A person false at heart may, when it suits his purposes, seize a stray truth here or there; but the relations of truth,—its perfectness,—that which makes it wholesome truth, he can never perceive. As wholeness and wholesomeness go together, so also sight with sincerity; it is only the constant desire of, and submissiveness to truth, which can measure its strange angles and mark its infinite aspects; and fit them and knit them into the strength of sacred invention. Sacred, I call it deliberately; for it is thus, in the most accurate senses, humble as well as helpful; meek in its receiving, as magnificent in its disposing; the name it bears being rightly given to invention formal, not because it forms, but because it finds. For you cannot find a lie; you must make it for yourself. False things may be imagined, and false things composed; but only truth can be invented. 1 The word in the uppermost note, to the right of the sun, is “red;” the others, “yellow,” “purple,” “cold” light gray. He always noted the colors of the skies in this way. 2 It is not so good a facsimile as those I have given from Durer, for the original sketch is in light pencil; and the thickening and delicate emphasis of
  • 81.
    the lines, onwhich nearly all the beauty of the drawing depended, cannot be expressed in the woodcut, though marked by a double line as well as I could. But the figure will answer its purpose well enough in showing Turner’s mode of sketching. 3 Thus, in the Holy Family of Titian, lately purchased for the National Gallery, the piece of St. Catherine’s dress over her shoulders is painted on the under dress, after that was dry. All its value would have been lost, had the slightest tint or trace of it been given previously. This picture, I think, and certainly many of Tintoret’s, are painted on dark grounds; but this is to save time, and with some loss to the future brightness of the color. 4 In cleaning the “Hero and Leander,” now in the National collection, these upper glazes were taken off, and only the black ground left. I remember the picture when its distance was of the most exquisite blue. I have no doubt the “Fire at Sea” has had its distance destroyed in the same manner. PART IX. OF IDEAS OF RELATION:—II. OF INVENTION SPIRITUAL. ————— CHAPTER I.
  • 82.
    THE DARK MIRROR. §1. In the course of our inquiry into the moral of landscape (Vol. III., chap. 17), we promised, at the close of our work, to seek for some better, or at least clearer, conclusions than were then possible to us. We confined ourselves in that chapter to the vindication of the probable utility of the love of natural scenery. We made no assertion of the usefulness of painting such scenery. It might be well to delight in the real country, or admire the real flowers and true mountains. But it did not follow that it was advisable to paint them. Far from it. Many reasons might be given why we should not paint them. All the purposes of good which we saw that the beauty of nature could accomplish, may be better fulfilled by the meanest of her realities than by the brightest of imitations. For prolonged entertainment, no picture can be compared with the wealth of interest which may be found in the herbage of the poorest field, or blossoms of the narrowest copse. As suggestive of supernatural power, the passing away of a fitful rain- cloud, or opening of dawn, are in their change and mystery more pregnant than any pictures. A child would, I suppose, receive a religious lesson from a flower more willingly than from a print of one, and might be taught to understand the nineteenth Psalm, on a starry night, better than by diagrams of the constellations. Whence it might seem a waste of time to draw landscape at all. I believe it is;—to draw landscape mere and solitary, however beautiful (unless it be for the sake of geographical or other science, or of historical record). But there is a kind of landscape which it is not inexpedient to draw. What kind, we may probably discover by considering that which mankind has hitherto contented itself with painting.
  • 83.
    § 2. Wemay arrange nearly all existing landscape under the following heads:— I. Heroic.—Representing an imaginary world, inhabited by men not perhaps perfectly civilized, but noble, and usually subjected to severe trials, and by spiritual powers of the highest order. It is frequently without architecture; never without figure-action, or emotion. Its principal master is Titian. II. Classical.—Representing an imaginary world, inhabited by perfectly civilized men, and by spiritual powers of an inferior order. It generally assumes this condition of things to have existed among the Greek and Roman nations. It contains usually architecture of an elevated character, and always incidents of figure-action and emotion. Its principal master is Nicolo Poussin. III. Pastoral.—Representing peasant life and its daily work, or such scenery as may naturally be suggestive of it, consisting usually of simple landscape, in part subjected to agriculture, with figures, cattle, and domestic buildings. No supernatural being is ever visibly present. It does not in ordinary cases admit architecture of an elevated character, nor exciting incident. Its principal master is Cuyp. IV. Contemplative.—Directed principally to the observance of the powers of Nature, and record of the historical associations connected with landscape, illustrated by, or contrasted with, existing states of human life. No supernatural being is visibly present. It admits every variety of subject, and requires, in general, figure incident, but not of an exciting character. It was not developed completely until recent times. Its principal master is Turner.1 § 3. These are the four true orders of landscape, not of course distinctly separated from each other in all cases, but very distinctly in typical examples. Two spurious forms require separate note.
  • 84.
    (a.) Picturesque.—This isindeed rather the degradation (or sometimes the undeveloped state) of the Contemplative, than a distinct class; but it may be considered generally as including pictures meant to display the skill of the artist, and his powers of composition; or to give agreeable forms and colors, irrespective of sentiment. It will include much modern art, with the street views and church interiors of the Dutch, and the works of Canaletto, Guardi, Tempesta, and the like. (b.) Hybrid.—Landscape in which the painter endeavors to unite the irreconcileable sentiment of two or more of the above-named classes. Its principal masters are Berghem and Wouvermans. § 4. Passing for the present by these inferior schools, we find that all true landscape, whether simple or exalted, depends primarily for its interest on connection with humanity, or with spiritual powers. Banish your heroes and nymphs from the classical landscape—its laurel shades will move you no more. Show that the dark clefts of the most romantic mountain are uninhabited and untraversed; it will cease to be romantic. Fields without shepherds and without fairies will have no gaiety in their green, nor will the noblest masses of ground or colors of cloud arrest or raise your thoughts, if the earth has no life to sustain, and the heaven none to refresh. § 5. It might perhaps be thought that, since from scenes in which the figure was principal, and landscape symbolical and subordinate (as in the art of Egypt), the process of ages had led us to scenes in which landscape was principal and the figure subordinate,—a continuance in the same current of feeling might bring forth at last an art from which humanity and its interests should wholly vanish, leaving us to the passionless admiration of herbage and stone. But this will not, and cannot be. For observe the parallel instance in the gradually increasing importance of dress. From the simplicity of Greek design, concentrating, I suppose, its skill chiefly on the naked form, the course of time developed conditions of Venetian imagination which found nearly as much interest,
  • 85.
    and expressed nearlyas much dignity, in folds of dress and fancies of decoration as in the faces of the figures themselves; so that if from Veronese’s Marriage in Cana we remove the architecture and the gay dresses, we shall not in the faces and hands remaining, find a satisfactory abstract of the picture. But try it the other way. Take out the faces; leave the draperies, and how then? Put the fine dresses and jewelled girdles into the best group you can; paint them with all Veronese’s skill: will they satisfy you? § 6. Not so. As long as they are in their due service and subjection— while their folds are formed by the motion of men, and their lustre adorns the nobleness of men—so long the lustre and the folds are lovely. But cast them from the human limbs;—golden circlet and silken tissue are withered; the dead leaves of autumn are more precious than they. This is just as true, but in a far deeper sense, of the weaving of the natural robe of man’s soul. Fragrant tissue of flowers, golden circlets of clouds, are only fair when they meet the fondness of human thoughts, and glorify human visions of heaven. § 7. It is the leaning on this truth which, more than any other, has been the distinctive character of all my own past work. And in closing a series of Art-studies, prolonged during so many years, it may be perhaps permitted me to point out this specialty—the rather that it has been, of all their characters, the one most denied. I constantly see that the same thing takes place in the estimation formed by the modern public of the work of almost any true person, living or dead. It is not needful to state here the causes of such error: but the fact is indeed so, that precisely the distinctive root and leading force of any true man’s work and way are the things denied concerning him. And in these books of mine, their distinctive character, as essays on art, is their bringing everything to a root in human passion or human hope. Arising first not in any desire to explain the principles of art, but in the
  • 86.
    endeavor to defendan individual painter from injustice, they have been colored throughout,—nay, continually altered in shape, and even warped and broken, by digressions respecting social questions, which had for me an interest tenfold greater than the work I had been forced into undertaking. Every principle of painting which I have stated is traced to some vital or spiritual fact; and in my works on architecture the preference accorded finally to one school over another, is founded on a comparison of their influences on the life of the workman—a question by all other writers on the subject of architecture wholly forgotten or despised. § 8. The essential connection of the power of landscape with human emotion is not less certain, because in many impressive pictures the link is slight or local. That the connection should exist at a single point is all that we need. The comparison with the dress of the body may be carried out into the extremest parallelism. It may often happen that no part of the figure wearing the dress is discernible, nevertheless, the perceivable fact that the drapery is worn by a figure makes all the difference. In one of the most sublime figures in the world this is actually so: one of the fainting Marys in Tintoret’s Crucifixion has cast her mantle over her head, and her face is lost in its shade, and her whole figure veiled in folds of gray. But what the difference is between that gray woof, that gathers round her as she falls, and the same folds cast in a heap upon the ground, that difference, and more, exists between the power of Nature through which humanity is seen, and her power in the desert. Desert— whether of leaf or sand—true desertness is not in the want of leaves, but of life. Where humanity is not, and was not, the best natural beauty is more than vain. It is even terrible; not as the dress cast aside from the body; but as an embroidered shroud hiding a skeleton. § 9. And on each side of a right feeling in this matter there lie, as usual, two opposite errors.
  • 87.
    The first, thatof caring for man only; and for the rest of the universe, little, or not at all, which, in a measure, was the error of the Greeks and Florentines; the other, that of caring for the universe only;—for man, not at all,—which, in a measure, is the error of modern science, and of the Art connecting itself with such science. The degree of power which any man may ultimately possess in landscape-painting will depend finally on his perception of this influence. If he has to paint the desert, its awfulness—if the garden, its gladsomeness—will arise simply and only from his sensibility to the story of life. Without this he is nothing but a scientific mechanist; this, though it cannot make him yet a painter, raises him to the sphere in which he may become one. Nay, the mere shadow and semblance of this have given dangerous power to works in all other respects unnoticeable; and the least degree of its true presence has given value to work in all other respects vain. The true presence, observe, of sympathy with the spirit of man. Where this is not, sympathy with any higher spirit is impossible. For the directest manifestation of Deity to man is in His own image, that is, in man. § 10. “In his own image. After his likeness.” Ad imaginem et similitudinem Suam. I do not know what people in general understand by those words. I suppose they ought to be understood. The truth they contain seems to lie at the foundation of our knowledge both of God and man; yet do we not usually pass the sentence by, in dull reverence, attaching no definite sense to it at all? For all practical purpose, might it not as well be out of the text? I have no time, nor much desire, to examine the vague expressions of belief with which the verse has been encumbered. Let us try to find its only possible plain significance.
  • 88.
    § 11. Itcannot be supposed that the bodily shape of man resembles, or resembled, any bodily shape in Deity. The likeness must therefore be, or have been, in the soul. Had it wholly passed away, and the Divine soul been altered into a soul brutal or diabolic, I suppose we should have been told of the change. But we are told nothing of the kind. The verse still stands as if for our use and trust. It was only death which was to be our punishment. Not change. So far as we live, the image is still there; defiled, if you will; broken, if you will; all but effaced, if you will, by death and the shadow of it. But not changed. We are not made now in any other image than God’s. There are, indeed, the two states of this image— the earthly and heavenly, but both Adamite, both human, both the same likeness; only one defiled, and one pure. So that the soul of man is still a mirror, wherein may be seen, darkly, the image of the mind of God. These may seem daring words. I am sorry that they do; but I am helpless to soften them. Discover any other meaning of the text if you are able;—but be sure that it is a meaning—a meaning in your head and heart;—not a subtle gloss, nor a shifting of one verbal expression into another, both idealess. I repeat, that, to me, the verse has, and can have, no other signification than this—that the soul of man is a mirror of the mind of God. A mirror dark, distorted, broken, use what blameful words you please of its state; yet in the main, a true mirror, out of which alone, and by which alone, we can know anything of God at all. “How?” the reader, perhaps, answers indignantly. “I know the nature of God by revelation, not by looking into myself.” Revelation to what? To a nature incapable of receiving truth? That cannot be; for only to a nature capable of truth, desirous of it, distinguishing it, feeding upon it, revelation is possible. To a being undesirous of it, and hating it, revelation is impossible. There can be none to a brute, or fiend. In so far, therefore, as you love truth, and live therein, in so far revelation can exist for you;—and in so far, your mind is the image of God’s.
  • 89.
    Welcome to ourwebsite – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com