1. Trang chủ
  2. » Công Nghệ Thông Tin

programming ios 6 3rd edition

1,2K 1,2K 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Programming iOS 6 3rd Edition
Tác giả Matt Neuburg
Người hướng dẫn Rachel Roumeliotis, Kristen Borg
Trường học O'Reilly Media, Inc.
Chuyên ngành Computer Science / Programming
Thể loại Sách hướng dẫn
Năm xuất bản 2013
Thành phố Sebastopol
Định dạng
Số trang 1.185
Dung lượng 20,44 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

297 Key–Value Coding 298 KVC and Outlets 300 Key Paths and Array Accessors 301 Memory Management 303 Principles of Cocoa Memory Management 303 The Golden Rules of Memory Management 305 W

Trang 3

Matt Neuburg

THIRD EDITIONProgramming iOS 6

Trang 4

Programming iOS 6, Third Edition

by Matt Neuburg

Copyright © 2013 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: Rachel Roumeliotis

Production Editor: Kristen Borg

Proofreader: O’Reilly Production Services

Indexer: Matt Neuburg

Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Matt Neuburg

March 2013: Third Edition

Revision History for the Third Edition:

2013-02-27: First release

See http://oreilly.com/catalog/errata.csp?isbn=9781449365769 for release details.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly

Media, Inc Programming iOS 6, 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 trade‐ mark 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 author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

ISBN: 978-1-449-36576-9

[LSI]

Trang 5

Table of Contents

Preface xvii

Part I Language 1 Just Enough C 3

Compilation, Statements, and Comments 5

Variable Declaration, Initialization, and Data Types 6

Structs 9

Pointers 11

Arrays 14

Operators 15

Flow Control and Conditions 17

Functions 21

Pointer Parameters and the Address Operator 24

Files 26

The Standard Library 30

More Preprocessor Directives 30

Data Type Qualifiers 31

2 Object-Based Programming 35

Objects 35

Messages and Methods 36

Classes and Instances 37

Class Methods 40

Instance Variables 41

The Object-Based Philosophy 42

3 Objective-C Objects and Messages 47

An Instance Reference Is a Pointer 47

iii

Trang 6

Instance References, Initialization, and nil 49

Instance References and Assignment 51

Instance References and Memory Management 52

Messages and Methods 54

Sending a Message 54

Declaring a Method 55

Nesting Method Calls 56

No Overloading 57

Parameter Lists 58

Unrecognized Selectors 59

Typecasting and the id Type 61

Messages as Data Type 65

C Functions 66

CFTypeRefs 67

Blocks 68

4 Objective-C Classes 75

Class and Superclass 75

Interface and Implementation 77

Header File and Implementation File 79

Class Methods 82

The Secret Life of Classes 83

5 Objective-C Instances 85

How Instances Are Created 85

Ready-Made Instances 85

Instantiation from Scratch 87

Nib-Based Instantiation 90

Polymorphism 91

The Keyword self 93

The Keyword super 97

Instance Variables and Accessors 98

Key–Value Coding 100

Properties 102

How to Write an Initializer 104

Part II IDE 6 Anatomy of an Xcode Project 109

New Project 110

The Project Window 112

iv | Table of Contents

Trang 7

The Navigator Pane 113

The Utilities Pane 118

The Editor 119

The Project File and Its Dependents 122

The Target 125

Build Phases 125

Build Settings 126

Configurations 128

Schemes and Destinations 129

From Project to App 131

Build Settings 133

Property List Settings 133

Nib Files and Storyboard Files 134

Other Resources 135

Code 137

Frameworks and SDKs 139

7 Nib Management 145

A Tour of the Nib-Editing Interface 146

The Dock 147

Canvas 148

Inspectors and Libraries 151

Nib Loading and File’s Owner 153

Making and Loading a Nib 154

Outlet Connections 156

More Ways to Create Outlets 161

More About Outlets 164

Action Connections 165

Additional Initialization of Nib-Based Instances 168

8 Documentation 171

The Documentation Window 172

Class Documentation Pages 174

Sample Code 177

Other Resources 178

Quick Help 178

Symbols 179

Header Files 180

Internet Resources 180

9 Life Cycle of a Project 183

Device Architecture and Conditional Code 183

Table of Contents | v

Trang 8

Localization 188

Editing Your Code 192

Autocompletion 193

Snippets 195

Fix-it and Live Syntax Checking 195

Navigating Your Code 196

Debugging 199

Caveman Debugging 199

The Xcode Debugger 202

Unit Testing 208

Static Analyzer 208

Clean 209

Running in the Simulator 210

Running on a Device 212

Profile and Device Management 215

Version Control 216

Instruments 219

Distribution 223

Ad Hoc Distribution 225

Final App Preparations 226

Icons in the App 226

Other Icons 227

Launch Images 228

Screenshots 230

Property List Settings 231

Submission to the App Store 233

Part III Cocoa 10 Cocoa Classes 239

Subclassing 239

Categories 242

Splitting a Class 243

Class Extensions 244

Protocols 245

Optional Methods 250

Some Foundation Classes 252

Useful Structs and Constants 252

NSString and Friends 253

NSDate and Friends 255

NSNumber 256

vi | Table of Contents

Trang 9

NSValue 257

NSData 257

Equality and Comparison 258

NSIndexSet 258

NSArray and NSMutableArray 259

NSSet and Friends 261

NSDictionary and NSMutableDictionary 262

NSNull 264

Immutable and Mutable 264

Property Lists 265

The Secret Life of NSObject 266

11 Cocoa Events 269

Reasons for Events 270

Subclassing 270

Notifications 272

Receiving a Built-In Notification 273

Unregistering 275

NSTimer 276

Delegation 277

Data Sources 280

Actions 281

The Responder Chain 283

Deferring Responsibility 284

Nil-Targeted Actions 285

Swamped by Events 286

Delayed Performance 289

Application Lifetime Events 292

12 Accessors and Memory Management 297

Key–Value Coding 298

KVC and Outlets 300

Key Paths and Array Accessors 301

Memory Management 303

Principles of Cocoa Memory Management 303

The Golden Rules of Memory Management 305

What ARC Is and What It Does 307

How Cocoa Objects Manage Memory 310

Autorelease 312

Memory Management of Instance Variables (Non-ARC) 316

Memory Management of Instance Variables (ARC) 320

Retain Cycles and Weak References 321

Table of Contents | vii

Trang 10

Unusual Memory Management Situations 324

Nib Loading and Memory Management 329

Memory Management of Global Variables 330

Memory Management of Pointer-to-Void Context Info 331

Memory Management of CFTypeRefs 332

Properties 335

Property Memory Management Policies 336

Property Declaration Syntax 338

Property Accessor Synthesis 340

Dynamic Accessors 342

13 Data Communication 347

Model–View–Controller 347

Instance Visibility 349

Visibility by Instantiation 350

Visibility by Relationship 351

Global Visibility 352

Notifications 353

Key–Value Observing 354

Part IV Views 14 Views 363

The Window 364

Subview and Superview 367

Visibility and Opacity 369

Frame 370

Bounds and Center 371

Transform 375

Layout 380

Autoresizing 381

Autolayout 383

Constraints in the Nib 393

Order of Layout Events 398

Autolayout and View Transforms 399

15 Drawing 403

UIImage and UIImageView 403

Graphics Contexts 409

UIImage Drawing 412

CGImage Drawing 414

viii | Table of Contents

Trang 11

CIFilter and CIImage 418

Drawing a UIView 421

Graphics Context Settings 423

Paths and Drawing 425

Clipping 429

Gradients 430

Colors and Patterns 432

Graphics Context Transforms 434

Shadows 436

Points and Pixels 437

Content Mode 438

16 Layers 441

View and Layer 442

Layers and Sublayers 444

Manipulating the Layer Hierarchy 446

Positioning a Sublayer 446

CAScrollLayer 447

Layout of Sublayers 448

Drawing in a Layer 449

Content Resizing and Positioning 452

Layers that Draw Themselves 455

Transforms 456

Depth 460

Shadows, Borders, and More 463

Layer Efficiency 464

Layers and Key–Value Coding 466

17 Animation 469

Drawing, Animation, and Threading 470

UIImageView and UIImage Animation 472

View Animation 475

Animation Blocks 475

Modifying an Animation Block 476

Transition Animations 480

Block-Based View Animation 481

Implicit Layer Animation 487

Animation Transactions 488

Media Timing Functions 489

Core Animation 491

CABasicAnimation and Its Inheritance 491

Using a CABasicAnimation 493

Table of Contents | ix

Trang 12

Keyframe Animation 497

Making a Property Animatable 498

Grouped Animations 499

Transitions 503

The Animations List 505

Animation and Autolayout 507

Actions 511

What an Action Is 511

The Action Search 511

Hooking Into the Action Search 513

Nonproperty Actions 516

Emitter Layers 517

CIFilter Transitions 523

18 Touches 527

Touch Events and Views 528

Receiving Touches 530

Restricting Touches 531

Interpreting Touches 532

Gesture Recognizers 537

Gesture Recognizer Classes 538

Multiple Gesture Recognizers 543

Subclassing Gesture Recognizers 544

Gesture Recognizer Delegate 546

Gesture Recognizers in the Nib 549

Touch Delivery 550

Hit-Testing 551

Initial Touch Event Delivery 556

Gesture Recognizer and View 556

Touch Exclusion Logic 558

Recognition 558

Touches and the Responder Chain 560

Part V Interface 19 View Controllers 565

The View Controller Hierarchy 568

View Controller and View Creation 572

Manual View 575

Generic Automatic View 578

View in a Separate Nib 579

x | Table of Contents

Trang 13

Nib-Instantiated View Controller 583

Storyboard-Instantiated View Controller 585

Rotation 588

Rotation and Layout Events 592

Initial Orientation 595

Presented View Controller 599

Presented View Animation 604

Presentation Styles 605

Rotation of a Presented View 608

Presenting a View in Response to Rotation 609

Tab Bar Controllers 610

Tab Bar Items 611

Configuring a Tab Bar Controller 612

Navigation Controllers 614

Bar Button Items 617

Navigation Items 619

Toolbar Items 622

Configuring a Navigation Controller 622

Page View Controller 625

Container View Controllers 630

Storyboards 633

Segues 635

Unwind Segues 637

Storyboards and Custom Container View Controllers 642

View Controller Lifetime Events 642

View Controller Memory Management 646

State Restoration 649

Participating in State Restoration 651

Restoration ID and Restoration Class 653

Restoring View Controller State 661

20 Scroll Views 667

Creating a Scroll View 667

Scrolling 673

Paging 676

Tiling 677

Zooming 679

Zooming Programmatically 682

Zooming with Detail 682

Scroll View Delegate 685

Scroll View Touches 687

Table of Contents | xi

Trang 14

Scroll View Performance 692

21 Table Views and Collection Views 695

Table View Cells 698

Built-In Cell Styles 699

Registering a Cell Class 705

Custom Cells 708

Table View Data 715

The Three Big Questions 716

Table View Sections 719

Refreshing Table View Data 726

Variable Row Heights 729

Table View Selection 732

Table View Scrolling and Layout 737

Table View State Restoration 738

Table View Searching 739

Table View Editing 745

Deleting Table Items 749

Editable Content in Table Items 750

Inserting Table Items 752

Rearranging Table Items 754

Dynamic Table Content 755

Table View Menus 756

Collection Views 758

22 Popovers and Split Views 767

Configuring and Displaying a Popover 769

Managing a Popover 774

Dismissing a Popover 774

Popovers and Presented Views 778

Popover Segues 778

Automatic Popovers 780

Split Views 782

23 Text 787

Attributed Strings 788

UILabel 797

UITextField 800

Summoning and Dismissing the Keyboard 803

Keyboard Covers Text Field 804

Configuring the Keyboard 808

Text Field Delegate and Control Event Messages 809

xii | Table of Contents

Trang 15

The Text Field Menu 812

UITextView 814

Core Text 817

24 Web Views 825

Loading Web View Content 826

Web View State Restoration 833

Communicating with a Web View 834

25 Controls and Other Views 837

UIActivityIndicatorView 837

UIProgressView 839

UIPickerView 841

UISearchBar 843

UIControl 847

UISwitch 852

UIStepper 853

UIPageControl 854

UIDatePicker 855

UISlider 858

UISegmentedControl 861

UIButton 865

Custom Controls 870

Bars 873

UINavigationBar 873

UIToolbar 878

UITabBar 879

Appearance Proxy 883

26 Modal Dialogs 887

Alert View 888

Action Sheet 891

Dialog Alternatives 896

Local Notifications 897

Activity View 900

Part VI Some Frameworks 27 Audio 909

System Sounds 909

Audio Session 910

Table of Contents | xiii

Trang 16

Interruptions 913

Routing Changes 915

Audio Player 916

Remote Control of Your Sound 918

Playing Sound in the Background 921

Further Topics in Sound 923

28 Video 925

MPMoviePlayerController 926

MPMoviePlayerViewController 932

UIVideoEditorController 934

Introduction to AV Foundation Video 936

29 Music Library 943

Exploring the Music Library 943

The Music Player 948

The Music Picker 954

30 Photo Library and Image Capture 957

UIImagePickerController 957

Choosing from the Photo Library 958

Using the Camera 962

Image Capture With AV Foundation 966

The Assets Library Framework 969

31 Address Book 973

Address Book Database 973

Address Book Interface 977

ABPeoplePickerNavigationController 978

ABPersonViewController 980

ABNewPersonViewController 981

ABUnknownPersonViewController 982

32 Calendar 985

Calendar Database 985

Calendar Interface 995

33 Mail and Messages 1003

Mail Message 1003

Text Message 1005

xiv | Table of Contents

Trang 17

Twitter Post 1006

34 Maps 1007

Displaying a Map 1007

Annotations 1010

Overlays 1017

Map Kit and Current Location 1024

Geocoding 1025

Communicating With the Maps App 1027

35 Sensors 1029

Location 1030

Heading 1035

Acceleration and Attitude 1036

Shake Events 1037

Raw Acceleration 1038

Gyroscope 1042

Part VII Final Topics 36 Persistent Storage 1051

The Sandbox 1052

Basic File Operations 1053

Saving and Reading Files 1054

User Defaults 1056

File Sharing 1058

Document Types 1059

Handing Off a Document 1060

The Document Architecture 1064

iCloud 1068

XML 1070

SQLite 1077

Core Data 1078

Image File Formats 1084

37 Basic Networking 1087

HTTP Requests 1087

Bonjour 1096

Push Notifications 1098

Table of Contents | xv

Trang 18

Beyond Basic Networking 1099

38 Threads 1101

The Main Thread 1101

Why Threading Is Hard 1104

Three Ways of Threading 1106

Manual Threads 1107

NSOperation 1109

Grand Central Dispatch 1114

Threads and App Backgrounding 1119

39 Undo 1123

The Undo Manager 1123

The Undo Interface 1127

The Undo Architecture 1130

40 Epilogue 1133

Index 1135

xvi | Table of Contents

Trang 19

Aut lego vel scribo; doceo scrutorve sophian.

—Sedulius Scottus

Preface

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 programmingframework to make applications for a touch-based device with limited memory andspeed 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 aninsight into the goals and mindset of those who created it When I first encounteredCocoa Touch, my assessment of its personality was: “Wow, the people who wrote thisare really clever!” On the one hand, the number of built-in interface widgets was severelyand deliberately limited; on the other hand, the power and flexibility of some of thosewidgets, 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 thattiny iPhone display to unfold virtually into multiple interface worlds within a single appwithout the user becoming lost or confused

Even more impressive, Apple took the opportunity to recreate and rationalize Cocoafrom the ground up as Cocoa Touch Cocoa itself is very old, having begun life asNeXTStep before Mac OS X even existed It has grown by accretion and with a certainconservatism in order to maintain something like backward compatibility With CocoaTouch, on the other hand, Apple had the opportunity to throw out the baby with thebath 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 independentcreature, a leaner, meaner, smarter Cocoa I could praise Cocoa Touch’s deliberate use

of systematization (and its healthy respect for Occam’s Razor) through numerous ex‐

xvii

Trang 20

amples Where Mac OS X’s animation layers are glommed onto views as a kind of af‐terthought, a Cocoa Touch view always has an animation layer counterpart Memorymanagement policies, such as how top-level objects are managed when a nib loads, aresimplified and clarified And so on.

At the same time, Cocoa Touch is still a form of Cocoa It still requires a knowledge ofObjective-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 Infact, it’s rather difficult

The popularity of the iPhone, with its largely free or very inexpensive apps, and thesubsequent popularity of the iPad, have brought and will continue to bring into the foldmany new programmers who see programming for these devices as worthwhile anddoable, even though they may not have felt the same way about Mac OS X Apple’s ownannual WWDC developer conventions have reflected this trend, with their emphasisshifted 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 givesthe programmer mighty powers that can seem as limitless as imagination itself, but italso has fundamentals I often see questions online from programmers who are evidentlydeep into the creation of some interesting app, but who are stymied in a way that revealsquite 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 toground the reader in the fundamentals of iOS I love Cocoa and have long wished towrite 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.”Here I have attempted to marshal and expound, in what I hope is a pedagogically helpfuland instructive yet ruthlessly Euclidean and logical order, the principles on which soundiOS programming rests, including a good basic knowledge of Objective-C (starting 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 communicationwith one another, and managed over their lifetimes, and a survey of the primary interfacewidgets and other common tasks My hope, as with my previous books, is that you willboth read this book cover to cover (learning something new often enough to keep youturning the pages) and keep it by you as a handy reference

This book is not intended to disparage Apple’s own documentation and exampleprojects 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 thatthey don’t fulfill the same function as a reasoned, ordered presentation of the facts Theonline documentation must make assumptions as to how much you already know; itcan’t guarantee that you’ll approach it in a given order And online documentation is

xviii | Preface

Trang 21

more suitable to reference than to instruction A fully written example, no matter howwell 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 assumeyou know C before you know Objective-C for the simple reason that Chapter 1 precedesChapter 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 “commonbeginner mistakes”; in most cases, these are mistakes that I have made myself, in addition

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 Iwas learning You’ll also see me construct many examples piece by piece or extract andexplain just one tiny portion of a larger app It is not a massive finished program thatteaches programming, but an exposition of the thought process that developed thatprogram It is this thought process, more than anything else, that I hope you will gainfrom reading this book

iOS is huge, massive, immense It’s far too big to be encompassed in a book even of thissize And in any case, that would be inappropriate and unnecessary There are entireareas of Cocoa Touch that I have ruthlessly avoided discussing Some of them wouldrequire an entire book of their own Others you can pick up well enough, when the timecomes, from the documentation This book is only a beginning — the fundamentals.But I hope that it will be the firm foundation that will make it easier for you to tacklewhatever lies beyond, in your own fun and rewarding iOS programming future

Conventions Used in This Book

The following typographical conventions are used in this book:

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

Preface | xix

Trang 22

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 inthis book in your programs and documentation You do not need to contact us forpermission 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 requirepermission Selling or distributing a CD-ROM of examples from O’Reilly books doesrequire permission Answering a question by citing this book and quoting example codedoes not require permission Incorporating a significant amount of example code fromthis book into your product’s documentation does require permission

We appreciate, but do not require, attribution An attribution usually includes the title,

author, publisher, and ISBN For example: “Programming iOS 6 by Matt Neuburg

(O’Reilly) Copyright 2013 Matt Neuburg, 978-1-449-36576-9.”

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 youeasily search over 7,500 technology and creative reference books andvideos to find the answers you need quickly

With a subscription, you can read any page and watch any video from our library online.Read books on your cell phone and mobile devices Access new titles before they areavailable for print, and get exclusive access to manuscripts in development and postfeedback for the authors Copy and paste code samples, organize your favorites, down‐load chapters, bookmark key sections, create notes, print out pages, and benefit fromtons of other time-saving features

O’Reilly Media has uploaded this book to the Safari Books Online service To have fulldigital 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

xx | Preface

Trang 23

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments for the First Edition

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 tothe Unicomp Model M keyboard (http://pckeyboard.com), without which I could nothave 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 Screenshotswere created with Snapz Pro X (http://www.ambrosiasw.com) and GraphicConverter(http://www.lemkesoft.com); diagrams were drawn with OmniGraffle (http:// www.omnigroup.com)

The splendid O’Reilly production process converted my AsciiDoc text files into PDFwhile 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 periodicupdates of the book as it grew, I would never have agreed to undertake this project inthe first place I would like particularly to thank Tools maven Abby Fox for her constantassistance

Preface | xxi

Trang 24

I have taken advice from two tech reviewers, Dave Smith and David Rowland, and havebeen assisted materially and spiritually by many readers who submitted errata and en‐couragement I was particularly fortunate in having Brian Jepson as editor; he providedenthusiasm 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 bookwithout the help of Nancy Kotary, and I didn’t intend to start now; her sharp eye hassmoothed the bristles of my punctuation-laden style For errors that remain, I takeresponsibility, of course

Notes on the Second Printing

For the second printing of this book, screenshots have been rendered more legible, and

a major technical error in the presentation of key–value coding in Chapter 5 has beencorrected In addition, numerous small emendations have been made; many of thesehave resulted from errata submissions by my readers, whom I should like to thank onceagain for their continued assistance and kind support Please note that these changeshave altered the pagination of the printed and PDF editions of the book

Acknowledgments for the Second Edition

Not surprisingly, I’d like to thank once again my editor, Brian Jepson, who made mewrite this new edition You can put down the whip now, Brian Thanks also to theO’Reilly team for their many-faceted assistance, and always to my readers for theirenthusiasm, encouragement, loyalty, and suggestions

Notes on the Second Edition

In order to describe the relationship of the second edition of this book with the firstedition, it will help if I first recap the recent history of iOS and Xcode versions

At the time I started writing the first edition this book, system versions 3.1.3 (on theiPhone) and 3.2 (on the iPad) were current As I was working on the book, iOS 4 andthe iPhone 4 came into being, but iOS 4 didn’t yet run on the iPad Subsequently iOS4.2 emerged; this was the first system able to run on both the iPhone and the iPad Atthe same time, Xcode was improved up to 3.2.5 iOS 4 was the first version of the system

to support multitasking, which necessitated much scurrying about on the part of de‐velopers, to adapt their apps to the new world order

Just in time for my final revisions of the first edition, Xcode 3.2.6 and iOS 4.3 werereleased, along with the first public version of the long-awaited Xcode 4 Xcode 4 was

a thorough overhaul of the IDE: menus, windows, and preferences are quite differentfrom Xcode 3.2.x Both Xcode 4 and Xcode 3.2.x can coexist on the same machine (upthrough Snow Leopard) and can be used to work on the same project; moreover, Xcode

xxii | Preface

Trang 25

3.2.x has some specialized capabilities that Xcode 4 lacks, so some long-standing de‐velopers may well continue to use it This situation presents a dilemma for an authordescribing the development process However, for iOS programming, I recommendadoption of Xcode 4, and the first edition of this book assumed that the reader hadadopted it.

Such was the situation in May 2011, when the first edition was formally released, de‐scribing how to program iOS 4

Less than five months later, in October 2011, Apple released iOS 5 Some of the featuresthat are new in iOS 5 are dramatic and pervasive, and it is this fact which has necessitated

a full revision of this book At the same time, Apple also released Xcode 4.2, and thisbook assumes that you are using that version of Xcode (or later), since it is the earliestversion of Xcode on which iOS 5 development is officially possible (It may be that, bydeep trickery, one can develop for iOS 5 using an earlier version of Xcode, but thatwould constitute unsupported behavior.) The first edition had a few mentions of menucommands and other interface in Xcode 3.2.x, but they have been excised from thisedition Xcode 4.2 comes in two flavors, depending whether you’re running SnowLeopard (Mac OS X 10.6) or Lion (Mac OS X 10.7) on your development machine; theyare supposed to behave more or less identically, but in fact each has its own bugs, so feelfree to try both

As I was finishing the second edition, in February 2012, Xcode 4.3 was released (forLion only) Its chief innovation has to do with the organization of files on disk: instead

of arriving as an installer that creates a top-level Developer folder to hold its many

ancillary files and folders, Xcode 4.3 contains the Developer folder inside its file package

(you can see it with the Finder’s Show Package Contents command) So when I speak

of the Developer folder in this book, you would need to understand that I mean some‐

thing like /Applications/Xcode.app/Contents/Developer I have not found any other ma‐

jor differences between Xcode 4.2 and Xcode 4.3, and in this book I will sometimes say

“Xcode 4.2” to mean Xcode 4.2 or later

The chief purpose of this new edition, then, is to bring the book up to date for iOS 5.You, the reader, might be coming to iOS programming for the first time, so this editionassumes no prior knowledge of iOS 4 or any previous version On the other hand, you,like me, could be making the transition from iOS 4 to iOS 5, so this edition lays somespecial emphasis on features that are new in iOS 5 This emphasis could also be useful

to new iOS programmers who are thinking of writing apps that can also run under iOS

4 My goal, however, is not to burden the reader with outdated information The vastmajority of devices that could run iOS 4 have probably been updated to iOS 5, and youwill probably be right in assuming that there will plenty of iOS 5 users out there, withoutyour having to bother to target earlier systems And from a pedagogical point of view,

it seems counterproductive to describe how things used to be — especially as, if you’rereally interested, you can always consult the previous edition of this book! For this

Preface | xxiii

Trang 26

reason, some references to the state of things before iOS 4.2 have been excised from thisedition.

Here is a case in point, showing my attitude and pedagogical approach with regard tonew iOS 5 features in this edition iOS 5 introduces ARC (automatic reference counting),which changes the way in which Objective-C programmers manage object memory soprofoundly as to render Objective-C a different language Use of ARC is optional inprogramming iOS, but it is extraordinarily helpful to have it turned on, and in this book

I therefore assume throughout that you do have it turned on In Chapter 12, where Idiscuss memory management, I still describe what life is like without ARC, as I did inthe previous edition; but, outside that chapter, all code examples, unless specificallystated otherwise, are supposed to be running under ARC If you start a new Xcodeproject with File → New Project and pick any iOS application template, then if “UseAutomatic Reference Counting” is checked in the second screen, you’re using ARC iOS 5 also introduces storyboards A storyboard file is similar to a nib file: it’s a placewhere Xcode lets you “draw” parts of the interface The main difference is that a singlestoryboard file can do the work of multiple nib files Nib files and storyboard files arenot identical, nor are they used identically, but because of their similarity, when I speak

of a nib file generically, in this book, I mean a nib or storyboard file, indifferently I’lltry to indicate this at the time, but the reader will forgive me if I don’t keep saying “nib

or storyboard” all the time

In closing, I should like to say a few words to the people who have, in my opinion,gratuitously criticized the previous edition of this book on one or more of the followinggrounds:

a It isn’t a “cookbook” (a book full of step-by-step instructions for creating full work‐ing applications)

b It devotes hundreds of pages to fundamentals

c It doesn’t get the reader started early on with hands-on programming; there isn’teven a “Hello, World” tutorial

All of that is perfectly true It is also quite deliberate As both the table of contents andthis preface are at pains to make clear, this is not that type of book To paraphrase Butler’sLaw, this book is the type of book it is, and not some other type That’s why I wrote thisbook in the first place The books of the type that these critics seem to want this book

to be exist by the score; books of the type that this book is, however, seemed to me not

to exist at all As with all my other books, so with this one: when I couldn’t find the book

I wanted, I wrote it myself I expect this book to be useful to those who need this type

of book People who prefer some other type of book should get some other type of book,and not mar my book’s web page by criticizing it for not being what it was never intended

to be

xxiv | Preface

Trang 27

The purpose of this book is to proceed by focusing on the underlying knowledge neededfor an actual understanding of iOS programming That is precisely the opposite of acookbook This book has no simple recipes ready for you to drop into your own codeand come up with an app I don’t give you some fish; I teach you what a fish is and whatyou need to know to obtain one The number of books out there that skip blithely pastthe fundamentals, leaving the reader to pick up Objective-C somehow independently,

is painfully huge The result is that numerous learners are encouraged to try their hand

at programming when, to judge from the nature of the questions they ask and the con‐fusion they exhibit, they don’t understand what they are doing

This book acts as a corrective, which in turn requires that space be devoted to funda‐mentals The book does not hold a gun to your head and force you to read all about all

of those fundamentals; if you already know everything there is to know about C, about Objective-C, about Xcode, about Cocoa, about views and drawing or whatever (but do you? do you really?), then by all means, skip those opening chapters But don’t begrudge

to the people who need them the explanations that this book contains, as those are thepeople at whom they are aimed

That explains why there’s no attempt, in this book, to rush the reader into hands-onprogramming My book does not pander to a desire for the false, cheap gratification ofmaking believe that one is a programmer merely because one can parrot some instruc‐

tions My book is about knowledge — hard-won, rigorously gained knowledge It’s about

gaining an understanding of what you are doing when you program iOS 5 It calls for

a substantial investment of time and thought, and many pages elapse before any practicalprogramming is demonstrated

Perhaps part of the misunderstanding here is that the critic has not noticed, or has notunderstood, the sentence earlier in this Preface stating that my book is written in “apedagogically helpful and instructive yet ruthlessly Euclidean and logical order.” Somepeople may not know or appreciate what “Euclidean” means It means “in the manner

of Euclid.” Euclid wrote our first surviving mathematical textbook, and it is distin‐guished by the following remarkable characteristic, among others: if concept or asser‐tion B depends upon concept or assertion A, A comes first Nothing is postponed; Euclidnever says, “I’ll explain/prove/discuss this point later, but for now, just take my wordfor it.” I have attempted to copy Euclid’s model So, to take an obvious example, all realiOS apps use view controllers It’s true, then, that the reader isn’t told what’s involved inconstructing a real iOS app until Chapter 19 is reached and view controllers are dis‐cussed But to understand view controllers, you need to know what’s being controlled,namely, a view; hence Chapter 14 and the rest of Part IV And to grasp the relationshipbetween a view controller and its view, you need to know about Cocoa’s architecturalpatterns, such as lifetime events and the responder chain; hence Chapter 11 and the rest

of Part III Moreover, a view controller’s view is often loaded from a nib; hence Chap‐ter 7 And all of that requires a knowledge of the programming language you’ll be using,

Preface | xxv

Trang 28

Objective-C; hence Chapter 3 But Objective-C is C; hence Chapter 1 So to reach viewcontrollers any sooner would have been impossible I rest my case.

Anyway, the complaint that the reader of my book doesn’t get to run any code is factuallyfalse The book is crammed full of substantial code examples — all of which are availablefor download from my GitHub site (https://github.com/mattneub), so you can obtainthem, run them in Xcode, and play with them to your heart’s content So you can andshould, in fact, be running code right from the outset Nevertheless, the purpose of thecode in this book is not for the fun of running it All of my code is to support your

understanding of whatever concepts I’m explaining at that point in the book.

In any case, perfectly good hands-on “Hello, World” tutorials are a dime a dozen; they’replastered all over the Internet, including at Apple’s own site (http://developer.apple.com/ library/ios/#documentation/iPhone/Conceptual/iPhone101/Articles/) You don’t need

me to show you that the process of writing a trivial iPhone application is fun and easy.Still, for those who feel strongly that I haven’t done my job unless I supply a “Hello,World” example, here is one, complete with step-by-step instructions:

1 Install Xcode, and launch the Xcode application

2 Choose File → New → Project

3 In the “Choose a template” dialog, under “iOS” on the left (not “Mac OS X”), clickApplication On the right, click Empty Application Click Next

4 For Product Name, type Hello Enter a company identifier if there isn’t one already,such as com.yourLastName.yourFirstName Choose Device Family: iPhone Un‐check all three checkboxes Click Next

5 Navigate to the Desktop Uncheck “Create local git repository.” Click Create

6 The project window opens Press Command-1 At the left, click AppDelegate.m.

7 Work in the editor in the middle of the window Look for the words “Override pointfor customization after application launch.” Place the cursor to the right of thosewords and hit Return a few times, to make some white space Click in that whitespace and type these lines of code:

UILabel* label = [[UILabel alloc] init];

label.text = @"Hello, world!";

8 Press Command-R If you see a dialog asking whether you want to save, accept

9 After a while, the iOS Simulator application appears, containing a white windowwith “Hello, world!” in it

xxvi | Preface

Trang 29

Congratulations You’ve made a “Hello, world” example Wasn’t that easy? Wasn’t itboring? Wasn’t it pointless? And are you any the wiser as to what, in fact, you just did?

To find out — and, even more important, to know enough to be able to progress further

on your own — read this book

Acknowledgments for the Third Edition

This edition was written in the full public gaze, and I’d like to thank, as always, my manysharp-eyed readers who assisted me by spotting mistakes and making suggestions Iwould also like to say a word for wonderful, wonderful git (http://git-scm.com), as well

as the extraordinary SourceTree (http://www.sourcetreeapp.com)

At O’Reilly Media, I am grateful to XSL and CSS wizard Sarah Schneider, who brilliantlyand quickly tweaked the automated layout process to make this book look great inprinted and PDF form

Notes on the Third Edition

Shortly after the official release of iOS 6 and Xcode 4.5, I began revising the code ex‐amples in this book (available at https://github.com/mattneub) to use and demonstratethe new iOS features When that was done, I proceeded to rewrite the book text; while

I was doing so, iOS 6.1 and Xcode 4.6 were released, so those are the versions that thebook now assumes you’re using

For this third edition, I have eliminated most references to previous iOS versions ManyiOS 6 features, of course, do not exist in iOS 5 or before; I usually mention that a newfeature is new, but I have not generally addressed the problem of writing backwards-compatible code The text would become confusing and bloated if everything had to bequalified with advice for different versions (“but if you’re targeting iOS 5.1, do this; ifyou’re targeting iOS 5.0, do that; if you’re targeting iOS 4.3, do the other”) I believe Ican justify such omission on the grounds that the previous editions of this book exist!

If you’re targeting iOS 5, I’ve already described what to do, in the second edition; there’s

no need to repeat myself here

New iOS 6 features are, of course, both explained and adopted in this edition For ex‐ample, having described NSArray subscripting (in Chapter 10), I then use it consistently,

in place of objectAtIndex:, throughout the rest of the book Aside from this, the book’sstructure remains the same as in previous editions, growing where necessary to ac‐commodate explanations of new features, such as autolayout (in Chapter 14), state re‐storation (in Chapter 19), and collection views (in Chapter 21) Also, in response toreader requests, I have inserted a short example of Core Data programming into Chap‐ter 36

Preface | xxvii

Trang 31

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 themost 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 andouts 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

• Chapter 2 prepares the ground for Objective-C, by discussing object-based pro‐gramming in general architectural terms It also explains some extremely importantwords that will be used throughout the book, along with the concepts that lie behindthem

• Chapter 3 introduces the basic syntax of Objective-C

• Chapter 4 continues the explanation of Objective-C, discussing the nature ofObjective-C classes, with emphasis on how to create a class in code

• Chapter 5 completes the introduction to Objective-C, discussing how instances arecreated and initialized, along with an explanation of such related topics as poly‐morphism, instance variables, accessors, self and super, key–value coding, andproperties

We’ll return in Part III to a description of further aspects of the Objective-C language

— those that are particularly bound up with the Cocoa frameworks

Trang 33

Do you believe in C? Do you believe in anything

that has to do with me?

—Leonard Bernstein and Stephen Schwartz,

Mass

CHAPTER 1 Just Enough C

To program for iOS, you need to speak to iOS Everything you say to iOS will be in

accordance with the iOS API (An API, for application programming interface, is a list

or specification of things you are allowed to say when communicating.) Therefore, youwill need some knowledge of the C programming language, for two reasons:

• Most of the iOS API involves the Objective-C language, and most of your iOSprogramming 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 toneglect 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 rectangle

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 documentation

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 (Ritchiewas the creator of C) It is one of the best computer books ever written: brief, dense, andstunningly 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.gbdir ect.co.uk/c_book/

3

Trang 34

It would be impossible, and unnecessary, for me to describe all of C in a single chapter.

C is not a large or difficult language, but it has some tricky corners and can be extremelysubtle, powerful, and low-level Moreover, since C is described fully and correctly in themanuals I’ve just mentioned, it would be a mistake for me to repeat what they can tellyou better than I

You don’t have to know all about C in order to use Objective-C effectively, though; so

my purpose in this chapter is to outline those aspects of C that are important for you tounderstand 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 Just keep in mind that this chapter is not a technical manual of C.

If you know no C at all, I suggest that, as an accompaniment to this chapter, you alsoread select parts of K&R (think of this as “C: The Good Parts Version”) Here’s myproposed 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’tneed to read the rest of Chapter 5 because you won’t typically be doing any pointerarithmetic, 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 seeingand 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’llneed 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 mayfind 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 Cthat forms the basis of Objective-C Developments subsequent to K&R have resulted infurther 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 GNU99, which is itself anextension of C99 (though you could specify another C standard if you really wantedto) Fortunately, the most important differences between K&R’s C and Xcode’s C aresmall, convenient improvements that are easily remembered, so K&R remains the bestand most reliable C reference

4 | Chapter 1: Just Enough C

Trang 35

Compilation, Statements, and Comments

C is a compiled language You write your program as text; to run the program, thingsproceed in two stages First your text is compiled into machine instructions; then thosemachine instructions are executed Thus, as with any compiled language, you can maketwo kinds of mistake:

• 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 guaranteethat you haven’t made some other sort of mistake, which can be detected only bynoticing that the program doesn’t behave as intended

The C compiler is fussy, but you should accept its interference with good grace Thecompiler is your friend: learn to love it It may emit what looks like an irrelevant orincomprehensible 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 canwarn 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 beignored

I have said that running a program requires a preceding stage: compilation But in factthere is a third stage that precedes compilation: preprocessing (It doesn’t really matterwhether 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 thecompiler, it is not identical to the text you wrote Preprocessing might sound tricky andintrusive, but in fact it proceeds only according to your instructions and is helpful formaking your code clearer and more compact

Xcode allows you to view the effects of preprocessing on your program text (chooseProduct → Generate Output → Preprocessed File), so if you think you’ve made a mistake

in instructing the preprocessor, you can track it down I’ll talk more later about some

of the things you’re likely to say to the preprocessor

C is a statement-based language; every statement ends in a semicolon (Forgetting thesemicolon is a common beginner’s mistake.) For readability, programs are mostly writ‐ten with one statement per line, but this is by no means a hard and fast rule: longstatements (which, unfortunately, arise very often because of Objective-C’s verbosity)are commonly split over multiple lines, and extremely short statements are sometimeswritten 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 Indentation is linguistically meaninglessand is purely a matter of convention (and C programmers argue over those conventionswith near-religious fervor); Xcode helps “intelligently” by indenting automatically, and

Compilation, Statements, and Comments | 5

Trang 36

you can use its automatic indentation both to keep your code readable and to confirmthat you’re not making any basic syntactic mistakes.

Comments are delimited in K&R C by /* */; the material between the delimiterscan 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 everythingafter 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 forbrief comments than the K&R comment syntax

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 low‐ercase “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, giving thevariable a value; 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

6 | Chapter 1: Just Enough C

Trang 37

must precede all other statements, but in modern versions of C, this rule is relaxed sothat you don’t have to declare a variable until just before you start using it:

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), floatand double (floating-point numbers), and varieties such as short (short integer), long(long integer), unsigned short, and so on A numeric literal may optionally express itstype through a suffixed letter or letters: for example, 4 is an int, but 4UL is an unsignedlong; 4.0 is a double, but 4.0f is a float Objective-C makes use of some further numerictypes derived from the C numeric types (by way of the typedef statement, K&R 6.7)designed to respond to the question of whether the processor is 64-bit; the most im‐portant of these are NSInteger (along with NSUInteger) and CGFloat You don’t need

to use them explicitly unless an API tells you to, and even when you do, just think ofNSInteger 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 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 assigningnames to a sequence of numeric values and is useful when a value represents one ofseveral possible options The Cocoa API uses this device a lot For example, the threepossible types of status bar animation are defined like this:

That definition assigns the value 0 to the name UIStatusBarAnimationNone, the value

1 to the name UIStatusBarAnimationFade, and the value 2 to the name AnimationSlide The upshot is that you can use the suggestively meaningful nameswithout caring about, or even knowing, the arbitrary numeric values they represent It’s

UIStatusBar-a useful idiom, UIStatusBar-and you mUIStatusBar-ay well hUIStatusBar-ave reUIStatusBar-ason to define enums in your own code

Variable Declaration, Initialization, and Data Types | 7

Trang 38

Modern Enum Notation

Starting with LLVM compiler version 4.0, which made its debut in Xcode 4.4,

Objective-C extends the enum notation ever so slightly The status bar animation types, for ex‐ample, are now defined like this:

typedef NS_ENUM(NSInteger, UIStatusBarAnimation) {

typedef enum UIStatusBarAnimation : NSInteger UIStatusBarAnimation;

enum UIStatusBarAnimation : NSInteger {

of integer value is being used here (it’s an NSInteger) This makes UIStatusBarAnimation

a little more like a genuine data type It also lets Xcode help you more intelligently —for example, when performing code completion, as discussed in Chapter 9 Anothermacro, NS_OPTIONS, evaluates in Objective-C as a synonym of NS_ENUM (they are distinctonly in C++ code, which is not discussed in this book)

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 youcan write a string literal like this:

@"string"

8 | Chapter 1: Just Enough C

Trang 39

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 causingyour expression to be interpreted as a C string, which is a completely different animal.Because the notation for literal NSStrings is modeled on the notation for C strings, it isworth knowing something about C strings, even though you won’t generally encounterthem For example, K&R lists a number of escaped characters (K&R 2.3), which youcan also use in a literal NSString, including the following:

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 non-ASCII character directly into an NSString literal, and you

should ignore old Internet postings (and even an occasional sentence

in Apple’s own documentation) warning that it is not

K&R also mention a notation for concatenating string literals, in which multiple stringliterals separated only by white space are automatically concatenated and treated as asingle string literal This notation is useful for splitting a long string into multiple linesfor legibility, and Objective-C copies this convention for literal NSStrings as well, exceptthat you have to remember the at-sign:

@"This is a big long literal string "

@"which I have broken over two lines of code.";

Structs | 9

Trang 40

A C structure, usually called a struct (K&R 6.1), is a compound data type: it combinesmultiple 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 The iOS APIhas many commonly used structs, typically accompanied by convenience functions forworking with them.

For example, the iOS documentation tells you that a CGPoint is defined as follows:

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 oftwo simple native data types; in effect, a CGPoint has two CGFloat parts, and their namesare x and y (The rather odd-looking last line merely asserts that one can use the termCGPoint 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 to set this part of the struct, we can say myPoint.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 Toillustrate, 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 ThenmyRect.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 justthe width part of our CGRect directly, like this:

myRect.size.width = 8.6;

10 | Chapter 1: Just Enough C

Ngày đăng: 05/05/2014, 12:15

TỪ KHÓA LIÊN QUAN