Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Ios 9 programming fundamentals with swift
PREMIUM
Số trang
604
Kích thước
5.9 MB
Định dạng
PDF
Lượt xem
1480

Ios 9 programming fundamentals with swift

Nội dung xem thử

Mô tả chi tiết

Matt Neuburg

iOS 9

Programming

Fundamentals

with Swift

SWIFT, XCODE, AND COCOA BASICS

Covers iOS 9,

Xcode 7, and Swift 2.0

MOBILE DEVELOPMENT / IOS

iOS 9 Programming Fundamentals with Swift

ISBN: 978-1-491-93677-1

US $49.99 CAN $57.99

“Neuburg is my favorite

programming book

writer, period.”

—John Gruber

Daring Fireball

Matt Neuburg has a PhD in Classics

and has taught at many colleges and

universities. He has served as editor

of MacTech magazine and as contrib￾uting editor for TidBITS. He has writ￾ten many OS X and iOS applications.

Previous books include Programming

iOS 8, REALbasic: The Definitive Guide,

and AppleScript: The Definitive Guide.

Twitter: @oreillymedia

facebook.com/oreilly

Move into iOS development by getting a firm grasp of its fundamentals,

including the Xcode IDE, the Cocoa Touch framework, and Swift 2.0—the

latest version of Apple's acclaimed programming language. With this

thoroughly updated guide, you'll learn Swift’s object-oriented concepts,

understand how to use Apple's development tools, and discover how

Cocoa provides the underlying functionality iOS apps need to have.

■ Explore Swift’s object-oriented concepts: variables and

functions, scopes and namespaces, object types and instances

■ Become familiar with built-in Swift types such as numbers,

strings, ranges, tuples, Optionals, arrays, dictionaries, and sets

■ Learn how to declare, instantiate, and customize Swift object

types—enums, structs, and classes

■ Discover powerful Swift features such as protocols and generics

■ Catch up on Swift 2.0 innovations: option sets, protocol

extensions, error handling, guard statements, availability

checks, and more

■ Tour the lifecycle of an Xcode project from inception to App Store

■ Create app interfaces with nibs and the nib editor, Interface Builder

■ Understand Cocoa’s event-driven model and its major design

patterns and features

■ Find out how Swift communicates with Cocoa’s C and

Objective-C APIs

Once you master the fundamentals, you'll be ready to

tackle the details of iOS app development with author

Matt Neuburg's companion guide, Programming iOS 9.

Programming iOS 9

978-1-491-93685-6

Matt Neuburg

Boston

SECOND EDITION

iOS 9 Programming

Fundamentals with Swift

Swift, Xcode, and Cocoa Basics

iOS 9 Programming Fundamentals with Swift, Second Edition

by Matt Neuburg

Copyright © 2016 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://safaribooksonline.com). For more information, contact our corporate/

institutional sales department: 800-998-9938 or [email protected].

Editor: Rachel Roumeliotis

Production Editor: Kristen Brown

Proofreader: O’Reilly Production Services

Indexer: Matt Neuburg

Cover Designer: Karen Montgomery

Interior Designer: David Futato

Illustrator: Matt Neuburg

April 2015: First Edition

October 2015: Second Edition

Revision History for the Second Edition:

2015-09-23: First release

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

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 9 Programming Fundamentals with

Swift, the image of a harp seal, and related trade dress are trademarks of O’Reilly Media, Inc.

While the publisher and the author have used good faith efforts to ensure that the information and instruc‐

tions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors

or omissions, including without limitation responsibility for damages resulting from the use of or reliance

on this work. Use of the information and instructions contained in this work is at your own risk. If any code

samples or other technology this work contains or describes is subject to open source licenses or the intel‐

lectual property rights of others, it is your responsibility to ensure that your use thereof complies with such

licenses and/or rights.

ISBN: 978-1-491-93677-1

[LSI]

Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Part I. Language

1. The Architecture of Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Ground of Being 3

Everything Is an Object? 5

Three Flavors of Object Type 6

Variables 6

Functions 8

The Structure of a Swift File 9

Scope and Lifetime 11

Object Members 12

Namespaces 13

Modules 13

Instances 14

Why Instances? 16

self 19

Privacy 20

Design 21

Object Types and APIs 22

Instance Creation, Scope, and Lifetime 24

Summary and Conclusion 25

2. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Function Parameters and Return Value 27

Void Return Type and Parameters 30

iii

Function Signature 32

External Parameter Names 32

Overloading 35

Default Parameter Values 36

Variadic Parameters 37

Ignored Parameters 38

Modifiable Parameters 38

Function In Function 42

Recursion 44

Function As Value 44

Anonymous Functions 47

Define-and-Call 52

Closures 53

How Closures Improve Code 55

Function Returning Function 56

Closure Setting a Captured Variable 59

Closure Preserving Its Captured Environment 59

Curried Functions 61

3. Variables and Simple Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Variable Scope and Lifetime 63

Variable Declaration 65

Computed Initializer 67

Computed Variables 68

Setter Observers 71

Lazy Initialization 73

Built-In Simple Types 75

Bool 76

Numbers 77

String 85

Character 89

Range 93

Tuple 95

Optional 98

4. Object Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

Object Type Declarations and Features 111

Initializers 113

Properties 119

Methods 122

iv | Table of Contents

Subscripts 124

Nested Object Types 126

Instance References 127

Enums 129

Case With Fixed Value 130

Case With Typed Value 131

Enum Initializers 132

Enum Properties 134

Enum Methods 135

Why Enums? 136

Structs 137

Struct Initializers, Properties, and Methods 137

Struct As Namespace 139

Classes 139

Value Types and Reference Types 140

Subclass and Superclass 144

Class Initializers 150

Class Deinitializer 158

Class Properties and Methods 159

Polymorphism 161

Casting 164

Type Reference 168

Protocols 173

Why Protocols? 174

Protocol Type Testing and Casting 176

Declaring a Protocol 177

Optional Protocol Members 179

Class Protocol 180

Implicitly Required Initializers 181

Literal Convertibles 183

Generics 184

Generic Declarations 186

Type Constraints 188

Explicit Specialization 190

Associated Type Chains 191

Additional Constraints 194

Extensions 197

Extending Object Types 198

Extending Protocols 200

Extending Generics 203

Table of Contents | v

Umbrella Types 205

AnyObject 205

AnyClass 208

Any 209

Collection Types 210

Array 210

Dictionary 224

Set 229

5. Flow Control and More. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

Flow Control 235

Branching 236

Loops 248

Jumping 253

Operators 265

Privacy 268

Private Declaration 269

Public Declaration 271

Privacy Rules 272

Introspection 272

Memory Management 273

Weak References 275

Unowned References 276

Weak and Unowned References in Anonymous Functions 278

Memory Management of Protocol-Typed References 281

Part II. IDE

6. Anatomy of an Xcode Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

New Project 285

The Project Window 288

The Navigator Pane 289

The Utilities Pane 295

The Editor 296

The Project File and Its Dependents 299

The Target 301

Build Phases 302

Build Settings 304

Configurations 305

vi | Table of Contents

Schemes and Destinations 306

From Project to Running App 309

Build Settings 311

Property List Settings 312

Nib Files 313

Additional Resources 313

Code Files and the App Launch Process 316

Frameworks and SDKs 321

Renaming Parts of a Project 324

7. Nib Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325

The Nib Editor Interface 326

Document Outline 328

Canvas 330

Inspectors and Libraries 332

Nib Loading 334

When Nibs Are Loaded 334

Manual Nib Loading 336

Connections 338

Outlets 338

The Nib Owner 340

Automatically Configured Nibs 343

Misconfigured Outlets 344

Deleting an Outlet 345

More Ways to Create Outlets 346

Outlet Collections 349

Action Connections 350

More Ways to Create Actions 352

Misconfigured Actions 353

Connections Between Nibs — Not! 354

Additional Configuration of Nib-Based Instances 354

8. Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

The Documentation Window 360

Class Documentation Pages 362

Sample Code 365

Quick Help 366

Symbols 367

Header Files 368

Internet Resources 369

Table of Contents | vii

9. Life Cycle of a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371

Device Architecture and Conditional Code 371

Backward Compatibility 372

Device Type 374

Version Control 375

Editing and Navigating Your Code 377

Autocompletion 378

Snippets 380

Fix-it and Live Syntax Checking 381

Navigation 382

Finding 384

Running in the Simulator 385

Debugging 386

Caveman Debugging 386

The Xcode Debugger 389

Testing 395

Clean 401

Running on a Device 402

Running Without a Developer Program Membership 403

Obtaining a Developer Program Membership 404

Obtaining a Certificate 405

Obtaining a Development Provisioning Profile 407

Running the App 408

Profile and Device Management 409

Profiling 409

Gauges 410

Instruments 410

Localization 413

Localizing the Info.plist 414

Localizing a Nib File 416

Localizing Code Strings 418

Localizing With XML Files 420

Archiving and Distribution 422

Ad Hoc Distribution 424

Final App Preparations 426

Icons in the App 426

Other Icons 427

Launch Images 428

Screenshots and Video Previews 429

Property List Settings 430

viii | Table of Contents

Submission to the App Store 431

Part III. Cocoa

10. Cocoa Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437

Subclassing 437

Categories and Extensions 440

How Swift Uses Extensions 441

How You Use Extensions 441

How Cocoa Uses Categories 442

Protocols 443

Informal Protocols 445

Optional Methods 446

Some Foundation Classes 448

Useful Structs and Constants 448

NSString and Friends 450

NSDate and Friends 452

NSNumber 454

NSValue 455

NSData 456

Equality and Comparison 457

NSIndexSet 458

NSArray and NSMutableArray 459

NSDictionary and NSMutableDictionary 461

NSSet and Friends 462

NSNull 463

Immutable and Mutable 463

Property Lists 464

Accessors, Properties, and Key–Value Coding 465

Swift Accessors 466

Key–Value Coding 467

Uses of Key–Value Coding 468

KVC and Outlets 470

Key Paths 470

Array Accessors 471

The Secret Life of NSObject 472

11. Cocoa Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475

Reasons for Events 475

Table of Contents | ix

Subclassing 476

Notifications 477

Receiving a Notification 478

Unregistering 481

Posting a Notification 482

NSTimer 483

Delegation 484

Cocoa Delegation 484

Implementing Delegation 486

Data Sources 488

Actions 488

The Responder Chain 492

Deferring Responsibility 493

Nil-Targeted Actions 493

Key–Value Observing 494

Swamped by Events 498

Delayed Performance 501

12. Memory Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505

Principles of Cocoa Memory Management 505

Rules of Cocoa Memory Management 506

What ARC Is and What It Does 508

How Cocoa Objects Manage Memory 508

Autorelease Pool 509

Memory Management of Instance Properties 511

Retain Cycles and Weak References 512

Unusual Memory Management Situations 514

Nib Loading and Memory Management 519

Memory Management of CFTypeRefs 520

Property Memory Management Policies 521

Debugging Memory Management Mistakes 524

13. Communication Between Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525

Visibility by Instantiation 526

Visibility by Relationship 528

Global Visibility 529

Notifications and KVO 530

Model–View–Controller 531

A. C, Objective-C, and Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535

x | Table of Contents

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561

Table of Contents | xi

Preface

On June 2, 2014, Apple’s WWDC keynote address ended with a shocking announce‐

ment: “We have a new programming language.” This came as a huge surprise to the

developer community, which was accustomed to Objective-C, warts and all, and doubt‐

ed that Apple could ever possibly relieve them from the weight of its venerable legacy.

The developer community, it appeared, had been wrong.

Having picked themselves up off the floor, developers immediately began to examine

this new language — Swift — studying it, critiquing it, and deciding whether to use it.

My own first move was to translate all my existing iOS apps into Swift; this was enough

to convince me that, for all its faults, Swift deserved to be adopted by new students of

iOS programming, and that my books, therefore, should henceforth assume that readers

are using Swift.

The Swift language is designed from the ground up with these salient features:

Object-orientation

Swift is a modern, object-oriented language. It is purely object-oriented: “Every‐

thing is an object.”

Clarity

Swift is easy to read and easy to write, with minimal syntactic sugar and few hidden

shortcuts. Its syntax is clear, consistent, and explicit.

Safety

Swift enforces strong typing to ensure that it knows, and that you know, what the

type of every object reference is at every moment.

Economy

Swift is a fairly small language, providing some basic types and functionalities and

no more. The rest must be provided by your code, or by libraries of code that you

use — such as Cocoa.

xiii

Tải ngay đi em, còn do dự, trời tối mất!