Objective-C Fundamentals
Total Page:16
File Type:pdf, Size:1020Kb
Christopher K. Fairbairn Johannes Fahrenkrug Collin Ruffenach MANNING Objective-C Fundamentals Download from Wow! eBook <www.wowebook.com> Download from Wow! eBook <www.wowebook.com> Objective-C Fundamentals CHRISTOPHER K. FAIRBAIRN JOHANNES FAHRENKRUG COLLIN RUFFENACH MANNING SHELTER ISLAND Download from Wow! eBook <www.wowebook.com> For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email: [email protected] ©2012 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Troy Mott 20 Baldwin Road Technical editor: Amos Bannister PO Box 261 Copyeditor: Linda Kern Shelter Island, NY 11964 Proofreader: Katie Tennant Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781935182535 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 17 16 15 14 13 12 11 Download from Wow! eBook <www.wowebook.com> brief contents PART 1 GETTING STARTED WITH OBJECTIVE-C...........................1 1 ■ Building your first iOS application 3 2 ■ Data types, variables, and constants 28 3 ■ An introduction to objects 55 4 ■ Storing data in collections 74 PART 2 BUILDING YOUR OWN OBJECTS ....................................95 5 ■ Creating classes 97 6 ■ Extending classes 124 7 ■ Protocols 144 8 ■ Dynamic typing and runtime type information 163 9 ■ Memory management 177 PART 3 MAKING MAXIMUM USE OF FRAMEWORK FUNCTIONALITY ........................................................201 10 ■ Error and exception handling 203 11 ■ Key-Value Coding and NSPredicate 212 12 ■ Reading and writing application data 228 13 ■ Blocks and Grand Central Dispatch 257 14 ■ Debugging techniques 276 v Download from Wow! eBook <www.wowebook.com> Download from Wow! eBook <www.wowebook.com> contents preface xv acknowledgments xvi about this book xviii author online xxi about the cover illustration xxii PART 1 GETTING STARTED WITH OBJECTIVE-C ...............1 Building your first iOS application 3 1 1.1 Introducing the iOS development tools 4 Adapting the Cocoa frameworks for mobile devices 4 1.2 Adjusting your expectations 5 A survey of hardware specifications, circa mid-2011 6 Expecting an unreliable internet connection 7 1.3 Using Xcode to develop a simple Coin Toss game 7 Introducing Xcode—Apple’s IDE 8 Launching Xcode easily 8 ■ Creating the project 9 Writing the source code 12 1.4 Hooking up the user interface 15 Adding controls to a view 15 ■ Connecting controls to source code 17 vii Download from Wow! eBook <www.wowebook.com> viii CONTENTS 1.5 Compiling the Coin Toss game 21 1.6 Taking Coin Toss for a test run 21 Selecting a destination 22 ■ Using breakpoints to inspect the state of a running application 23 ■ Running the CoinToss game in the iPhone simulator 24 Controlling the debugger 25 1.7 Summary 27 Data types, variables, and constants 28 2 2.1 Introducing the Rental Manager application 29 Laying the foundations 29 2.2 The basic data types 32 Counting on your fingers—integral numbers 32 Filling in the gaps—floating-point numbers 35 Characters and strings 37 ■ Boolean truths 39 2.3 Displaying and converting values 40 NSLog and Format Specifiers 40 ■ Type casts and type conversions 43 2.4 Creating your own data types 44 Enumerations 44 ■ Structures 46 ■ Arrays 48 The importance of descriptive names 50 2.5 Completing Rental Manager v1.0, App Store here we come! 52 2.6 Summary 54 An introduction to objects 55 3 3.1 A whirlwind tour of object-oriented programming concepts 56 What’s wrong with procedural-based languages such as C? 56 What are objects? 56 ■ What are classes? 57 Inheritance and polymorphism 57 3.2 The missing data type: id 58 3.3 Pointers and the difference between reference and value types 59 Memory maps 59 ■ Obtaining the address of a variable 59 Following a pointer 60 ■ Comparing the values of pointers 61 Download from Wow! eBook <www.wowebook.com> CONTENTS ix 3.4 Communicating with objects 62 Sending a message to an object 62 ■ Sending a message to a class 63 ■ Sending nonexistent messages 64 Sending messages to nil 65 3.5 Strings 66 Constructing strings 66 ■ Extracting characters from strings 67 ■ Modifying strings 68 Comparing strings 69 3.6 Sample application 69 3.7 Summary 72 Storing data in collections 74 4 4.1 Arrays 75 Constructing an array 75 ■ Accessing array elements 76 Searching for array elements 77 ■ Iterating through arrays 79 Adding items to an array 80 4.2 Dictionaries 82 Constructing a dictionary 82 ■ Accessing dictionary entries 84 ■ Adding key/value pairs 85 Enumerating all keys and values 86 4.3 Boxing 88 The NSNumber class 89 ■ The NSValue class 90 nil vs. NULL vs. NSNull 90 4.4 Making the Rental Manager application data driven 91 4.5 Summary 94 PART 2 BUILDING YOUR OWN OBJECTS.........................95 Creating classes 97 5 5.1 Building custom classes 98 Adding a new class to the project 98 5.2 Declaring the interface of a class 99 Instance variables (ivars) 100 ■ Method declarations 101 Fleshing out the header file for the CTRentalProperty class 105 5.3 Providing an implementation for a class 106 Defining method implementations 106 ■ Accessing instance variables 106 ■ Sending messages to self 107 Fleshing out the method file for the CTRentalProperty class 108 Download from Wow! eBook <www.wowebook.com> x CONTENTS 5.4 Declared properties 109 @property syntax 109 ■ Synthesizing property getters and setters 112 ■ Dot syntax 113 5.5 Creating and destroying objects 115 Creating and initializing objects 115 ■ init is pretty dumb 116 Combining allocation and initialization 118 Destroying objects 119 5.6 Using the class in the Rental Manager application 120 5.7 Summary 123 Extending classes 124 6 6.1 Subclassing 124 What is subclassing? 125 6.2 Adding new instance variables 127 6.3 Accessing existing instance variables 129 Manual getters and setters approach 130 6.4 Overriding methods 131 Overriding the description method 132 6.5 Class clusters 134 Why use class clusters 134 ■ Multiple public clusters 135 6.6 Categories 136 Extending classes without subclassing 136 Using a category 136 ■ Considerations when using categories 138 6.7 Subclassing in your demo application 138 Creating and subclassing CTLease 139 Creating CTPeriodicLease as a subclass of CTLease 140 Creating CTFixedLease as a subclass of CTLease 141 6.8 Summary 143 Protocols 144 7 7.1 Defining a protocol 145 7.2 Implementing a protocol 146 Creating the protocol method callers 147 ■ Making a class conform to a protocol 148 Download from Wow! eBook <www.wowebook.com> CONTENTS xi 7.3 Important protocols 150 <UITableViewDataSource> 150 ■ <UITableViewDelegate> 153 <UIActionSheetDelegate> 157 ■ NSXMLParser 158 7.4 Summary 162 Dynamic typing and runtime type information 163 8 8.1 Static vs. dynamic typing 164 Making assumptions about the runtime type 164 8.2 Dynamic binding 166 8.3 How messaging works 166 Methods, selectors, and implementations 167 Handling unknown selectors 169 ■ Sending a message to nil 170 8.4 Runtime type information 171 Determining if a message will respond to a message 171 Sending a message generated at runtime 171 Adding new methods to a class at runtime 173 8.5 Practical uses of runtime type introspection 174 8.6 Summary 176 Memory management 177 9 9.1 Object ownership 178 9.2 Reference counting 179 Releasing an object 180 ■ Retaining an object 181 Determining the current retain count 182 9.3 Autorelease pools 184 What is an autorelease pool? 185 ■ Adding objects to the autorelease pool 185 ■ Creating a new autorelease pool 185 ■ Releasing objects in a pool 187 Why not use an autorelease pool for everything? 187 9.4 Memory zones 190 9.5 Rules for object ownership 192 9.6 Responding to low-memory warnings 193 Implementing the UIApplicationDelegate protocol 193 Overriding didReceiveMemoryWarning 194 ■ Observing the UIApplicationDidReceiveMemoryWarningNotification 197 9.7 Summary 199 Download from Wow! eBook <www.wowebook.com> xii CONTENTS PART 3 MAKING MAXIMUM USE OF FRAMEWORK FUNCTIONALITY.............................................201 Error and exception handling 203 10 10.1 NSError—handling errors the Cocoa way 204 Getting NSError to talk 204 ■ Examining NSError’s userInfo Dictionary 205 10.2 Creating NSError objects 206 Introducing RentalManagerAPI 206 ■ Handling and displaying RentalManagerAPI errors 209 10.3 Exceptions 210 Throwing exceptions 210 ■ Catching exceptions 211 10.4 Summary 211 Key-Value Coding and NSPredicate 212 11 11.1 Making your objects KVC-compliant