27,99 €
Get ready to create killer apps for iPad and iPhone on the new iOS 7! With Apple's introduction of iOS 7, demand for developers who know the new iOS will be high. You need in-depth information about the new characteristics and capabilities of iOS 7, and that's what you'll find in this book. If you have experience with C or C++, this guide will show you how to create amazing apps for iPhone, iPad, and iPod touch. You'll also learn to maximize your programs for mobile devices using iPhone SDK 7.0. Advanced topics such as security services, running on multiple iPlatforms, and local networking with Core Bluetooth are also covered. * Prepares experienced developers to create great apps for the newest version of Apple's iOS * Thoroughly covers the serious capabilities of iOS 7; information you need in order to make your apps stand out * Delves into advanced topics including how to control multitasking, security services, running apps on multiple iPlatforms and iDevices, enabling in-app purchases, advanced text layout, and building a core foundation * Also covers REST, advanced GCD, internationalization and localization, and local networking with Core Bluetooth iOS 7 Programming: Pushing the Limits will help you develop applications that take full advantage of everything iOS 7 has to offer.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 745
Veröffentlichungsjahr: 2014
Cover
Contents
Title Page
Copyright
Dedication
Publisher’s Acknowledgements
About the Authors
Acknowledgments
Introduction
Who This Book Is For
What This Book Covers
What Is New in This Edition
How This Book Is Structured
What You Need to Use This Book
Finding Apple Documentation
Source Code
Errata
Part I: What's New?
Chapter 1: The Brand New Stuff
The New UI
UIKit Dynamics and Motion Effects
Custom Transitions
New Multitasking Modes
Text Kit
Dynamic Type
MapKit Integration
SpriteKit
LLVM 5
Xcode 5
Others
Summary
Further Reading
Chapter 2: The World Is Flat: New UI Paradigms
Clarity, Deference, and Depth
Animations Animations Animations
Tint Colors
Layering and Context through Translucency
Dynamic Type
Custom Transitions
Transitioning (Migrating) Your App to iOS 7
Summary
Further Reading
Part II: Getting the Most Out of Everyday Tools
Chapter 3: You May Not Know
Naming Best Practices
Property and Ivar Best Practices
Categories
Associative References
Weak Collections
NSCache
NSURLComponents
CFStringTransform
instancetype
Base64 and Percent Encoding
-[NSArray firstObject]
Summary
Further Reading
Chapter 4: Storyboards and Custom Transitions
Getting Started with Storyboards
Custom Transitions
Summary
Further Reading
Chapter 5: Get a Handle on Collection Views
Collection Views
Advanced Customization with Collection View Custom Layout
Summary
Further Reading
Chapter 6: Stay in Bounds with Auto Layout
Auto Layout in Xcode 4
Getting Started with Auto Layout
What's New in Auto Layout in Xcode 5
Summary
Further Reading
Chapter 7: Better Custom Drawing
iOS's Many Drawing Systems
UIKit and the View Drawing Cycle
View Drawing Versus View Layout
Custom View Drawing
Optimizing UIView Drawing
Summary
Further Reading
Chapter 8: Layers Like an Onion: Core Animation
View Animations
Managing User Interaction
Drawing with Layers
Moving Things Around
Into the Third Dimension
Decorating Your Layers
Auto-Animating with Actions
Animating Custom Properties
Core Animation and Threads
Summary
Further Reading
Chapter 9: Two Things at Once: Multitasking
Introduction to Multitasking and Run Loops
Developing Operation-Centric Multitasking
Multitasking with Grand Central Dispatch
Summary
Further Reading
Part III: The Right Tool for the Job
Chapter 10: Building a (Core) Foundation
Core Foundation Types
Naming and Memory Management
Allocators
Introspection
Strings and Data
Collections
Toll-Free Bridging
Summary
Further Reading
Chapter 11: Behind the Scenes: Background Processing
Best Practices for Backgrounding: With Great Power Comes Great Responsibility
Important Backgrounding Changes in iOS 7
Network Access with NSURLSession
Periodic Fetching and Adaptive Multitasking
Waking Up in the Background
When We Left Our Heroes: State Restoration
Summary
Further Reading
Chapter 12: REST for the Weary
The REST Philosophy
Choosing Your Data Exchange Format
A Hypothetical Web Service
Important Reminders
RESTfulEngine Architecture (iHotelApp Sample Code)
Caching
Reasons for Going Offline
Strategies for Caching
Creating a Data Model Cache
Cache Versioning
Creating an In-Memory Cache
Creating a URL Cache
Summary
Further Reading
Apple Documentation
Books
Other Resources
Chapter 13: Getting More Out of Your Bluetooth Devices
History of Bluetooth
Why Bluetooth Low Energy?
Bluetooth SDK in iOS
Classes and Protocols
Working with a Bluetooth Device
Creating Your Own Peripherals
Running in the Background
Summary
Further Reading
Chapter 14: Batten the Hatches with Security Services
Understanding the iOS Sandbox
Securing Network Communications
Employing File Protection
Using Keychains
Using Encryption
Summary
Further Reading
Chapter 15: Running on Multiple iPlatforms, iDevices, and 64-bit Architectures
Developing for Multiple Platforms
Detecting Device Capabilities
In App Email and SMS
Supporting the New Class of 4-inch Devices (iPhone 5 and 5s)
Transitioning to iOS 7
Transitioning to 64-bit Architecture
UIRequiredDeviceCapabilities
Summary
Further Reading
Chapter 16: Reach the World: Internationalization and Localization
What Is Localization?
Localizing Strings
Auditing for Nonlocalized Strings
Formatting Numbers and Dates
Nib Files and Base Internationalization
Localizing Complex Strings
Summary
Further Reading
Chapter 17: Those Pesky Bugs: Debugging
LLDB
Debugging with LLDB
Breakpoints
Watchpoints
The LLDB Console
NSZombieEnabled Flag
Different Types of Crashes
Assertions
Exceptions
Collecting Crash Reports
Third-Party Crash Reporting Services
Summary
Further Reading
Chapter 18: Performance Tuning Until It Flies
The Performance Mindset
Welcome to Instruments
Finding Memory Problems
Finding CPU Problems
Drawing Performance
Optimizing Disk and Network Access
Summary
Further Reading
Part IV: Pushing the Limits
Chapter 19: Almost Physics: UIKit Dynamics
Animators, Behaviors, and Dynamic Items
UIKit “Physics”
Built-in Behaviors
Behavior Hierarchies
Custom Actions
Putting It Together: A Tear-Off View
Multiple Dynamic Animators
Interacting with UICollectionView
Summary
Further Reading
Chapter 20: Fantastic Custom Transitions
Custom Transitions in iOS 7
Transition Coordinators
Collection View and Layout Transitions
Custom View Controller Transitions Using Storyboards and Custom Segues
Custom View Controller Transition: The iOS 7 Way
Interactive Custom Transitions Using the iOS 7 SDK
Summary
Further Reading
Chapter 21: Fancy Text Layout
Understanding Rich Text
Attributed Strings
Dynamic Type
Text Kit
Core Text
Summary
Further Reading
Chapter 22: Cocoa’s Biggest Trick: Key-Value Coding and Observing
Key-Value Coding
Key-Value Observing
KVO Tradeoffs
Summary
Further Reading
Chapter 23: Beyond Queues: Advanced GCD
Semaphores
Dispatch Sources
Dispatch Timer Sources
Dispatch Once
Queue-Specific Data
Dispatch Data and Dispatch I/O
Summary
Further Reading
Chapter 24: Deep Objective-C
Understanding Classes and Objects
Working with Methods and Properties
Method Signatures and Invocations
How Message Passing Really Works
Method Swizzling
ISA Swizzling
Method Swizzling Versus ISA Swizzling
Summary
Further Reading
End User License Agreement
i
ii
iii
iv
v
vi
1
2
3
4
5
6
7
9
10
11
12
13
14
15
16
17
18
19
21
22
23
24
25
26
27
28
29
30
31
33
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
149
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
335
336
337
338
339
340
341
342
343
344
345
346
347
349
350
351
353
354
355
356
357
358
359
360
361
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
382
384
385
386
387
388
389
390
391
392
393
395
396
397
398
399
400
401
402
403
404
405
406
407
409
410
411
412
413
414
415
416
417
418
419
420
421
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
Chapter 1: The Brand New Stuff
Figure 1-1
: The area around the Timer tab of the Clock app shows a blurred black clock face behind it
Figure 1-2
: Xcode 5 showing the LLVM 5's Modules setting
Figure 1-3
: Xcode 5's debug navigator showing CPU usage of the currently running application
Figure 1-4
: Xcode 5's debug navigator showing memory usage of the currently running application
Figure 1-5
: Resizable areas within an Image set in an Asset Catalog
Figure 1-6
: Adding a test failure breakpoint
Chapter 2: The World Is Flat: New UI Paradigms
Figure 2-1
: Screenshot of the app running in iOS 7 before and after the popup is shown
Figure 2-2
: Calendar screen showing the screens that use custom transitions
Figure 2-3
: Screenshot showing the control buttons in iOS 7
Figure 2-4
: Interface Builder showing the option to extend your view below the translucent bars
Chapter 4: Storyboards and Custom Transitions
Figure 4-1
: New project template in Xcode 4.5 showing the Use Storyboard option
Figure 4-2
: Connecting an IBAction for unwinding a segue
Figure 4-3
: A storyboard illustrating static table view creation
Chapter 5: Get a Handle on Collection Views
Figure 5-1:
: Xcode showing a storyboard with a collection view and a prototype collection view cell
Figure 5-2
: Storyboard showing two cells, one for landscape images and another for portrait images
Figure 5-3
: Screenshot of iOS Simulator showing cell selection
Figure 5-4
: Default and Masonry layout in a collection view
Figure 5-5
: Collection View displaying same-sized cell
Figure 5-6
: Collection View displaying cells of random height
Figure 5-7
: Collection View displaying cells of random height but in Masonry layout
Chapter 6: Stay in Bounds with Auto Layout
Figure 6-1
: Xcode showing a storyboard with a UIDatePicker
Figure 6-2
: Output of the Date Picker running on 3.5-inch simulator
Figure 6-3:
: The Auto Layout Menu
Figure 6-4:
: Add New Constraints Popover
Figure 6-5:
: Xcode showing misplaced views
Figure 6-6:
: Adding a height constraint
Figure 6-7:
: Xcode highlighting design time and runtime layout
Figure 6-8:
: Xcode showing design and runtime layout for a label
Figure 6-9:
: Adding new constraints using Xcode
Chapter 7: Better Custom Drawing
Figure 7-1:
: How the Cocoa drawing cycle consolidates changes
Figure 7-2:
: Output of FlowerView
Figure 7-3:
: Comparison of line from {10,100} and line from {10,105.5}
Figure 7-4:
: Geometric line from {10, 100} to {200, 100}
Figure 7-5:
: Ideal three-pixel line
Figure 7-6:
: Anti-aliased three-pixel line
Figure 7-7:
: Filling the rectangle from {10,100} to {200,103}
Figure 7-8:
: Rotated FlowerView, mid-animation
Figure 7-9:
: Affine transforms
Figure 7-10:
: Drawing FlowerView in a 4 × 4 box
Figure 7-11:
: Simple scrolling graph
Figure 7-12:
: Text drawn with reverseImageForText:
Figure 7-13:
: Text that is pixel-aligned (top) and unaligned (bottom)
Chapter 8: Layers Like an Onion: Core Animation
Figure 8-1:
: CircleView animation
Figure 8-2:
: View and layer hierarchies
Figure 8-3:
: Effect of fill modes on media timing functions
Figure 8-4:
: Layer with colored, rounded border and shadow
Chapter 11: Behind the Scenes: Background Processing
Figure 11-1
: Background modes
Chapter 12: REST for the Weary
Figure 12-1
: Control flow in your view controller that implements on-demand caching
Chapter 14: Batten the Hatches with Security Services
Figure 14-1
: The certificate chain for daw.apple.com
Figure 14-2
: iOS App ID Settings
Figure 14-3
: Creating a keychain access group
Chapter 15: Running on Multiple iPlatforms, iDevices, and 64-bit Architectures
Figure 15-1
: Multitasking availability in developer documentation
Figure 15-2
: Multitasking availability in header file
Figure 15-3
: Xcode 4.5 prompting for addition of a launch image for iPhone 5
Figure 15-4
: Changing the autoresizing mask property using Interface Builder
Figure 15-5
: Changing Architectures from the Build Settings Editor
Chapter 16: Reach the World: Internationalization and Localization
Figure 16-1
: Localization workflow
Chapter 17: Those Pesky Bugs: Debugging
Figure 17-1
: The Debug Information Format setting in your target settings
Figure 17-2
: Adding an exception breakpoint
Figure 17-3
: Xcode breaking at a breakpoint you just set
Figure 17-4
: Adding a symbolic breakpoint
Figure 17-5
: Editing breakpoints
Figure 17-6
: Enabling Zombie objects
Chapter 18: Performance Tuning Until It Flies
Figure 18-1
: Allocations Instrument
Figure 18-2
: Extended Detail for Allocations
Figure 18-3
: Code View
Figure 18-4
: All Heap & Anonymous VM
Figure 18-5
: Event notifications in Instruments
Figure 18-6
: Improved memory management
Figure 18-7
: Memory footprint of ZipTextView with custom drawing
Figure 18-8
: Time Profiler analysis of ZipText
Figure 18-9
: ZipText with caching
Figure 18-10
: Core Animation instrument
Chapter 20: Fantastic Custom Transitions
Figure 20-1
: The built-in calendar app uses a custom transition when transitioning from one screen to another
Chapter 21: Fancy Text Layout
Figure 21-1
: Unique characters
Figure 21-2
: Unique glyphs
Figure 21-3
: Forms of HEH
Figure 21-4
: LAM + ALIF
Figure 21-5
: f + i
Figure 21-6
: Variations of Baskerville
Figure 21-7
: Rich text with continuous attribute ranges
Figure 21-8
: Text Size settings panel
Figure 21-9
: Accessibility settings panel
Figure 21-10
: Text drawn with an exclusion path
Figure 21-11
: Output of CurvyTextView
Figure 21-12
: Column layout using a single path
Chapter 24: Deep Objective-C
Figure 24-1
: Layout of an Objective-C object
Cover
Contents
Begin Reading
Rob Napier
Mugunth Kumar
This edition first published 2014
© 2014 Rob Napier and Mugunth Kumar.
Registered office
John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO198SQ, United Kingdom
For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com.
The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
DESIGNATIONS USED BY COMPANIES TO DISTINGUISH THEIR PRODUCTS ARE OFTEN CLAIMED AS TRADEMARKS. ALL BRAND NAMES AND PRODUCT NAMES USED IN THIS BOOK ARE TRADE NAMES, SERVICE MARKS, TRADEMARKS OR REGISTERED TRADEMARKS OF THEIR RESPECTIVE OWNERS. THE PUBLISHER IS NOT ASSOCIATED WITH ANY PRODUCT OR VENDOR MENTIONED IN THIS BOOK. THIS PUBLICATION IS DESIGNED TO PROVIDE ACCURATE AND AUTHORITATIVE INFORMATION IN REGARD TO THE SUBJECT MATTER COVERED. IT IS SOLD ON THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING PROFESSIONAL SERVICES. IF PROFESSIONAL ADVICE OR OTHER EXPERT ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL SHOULD BE SOUGHT.
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. Ltd. and/ or its affiliates in the United States and/or other countries, and may not be used without written permission. iPhone, iPad and iPod touch are trademarks of Apple Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Ltd. is not associated with any product or vendor mentioned in the book.
A catalogue record for this book is available from the British Library.
ISBN 978-1-118-81834-3 (pbk); ISBN 978-1-118-81832-9 (ebk); ISBN 978-1-118-81833-6 (ebk)
Set in 9.5/12 MyriadPro-Regular by TCS/SPS, Chennai, India
To the Neverwood Five. We’re getting the band back together.Rob
To my mother who shaped the first twenty years of my lifeMugunth
Some of the people who helped bring this book to market include the following:
Editorial and Production
VP Consumer and Technology Publishing Director: Michelle Leete
Associate Director–Book Content Management: Martin Tribe
Associate Publisher: Chris Webb
Executive Commissioning Editor: Craig Smith
Project Editor: Tom Dinse
Copy Editor: Chuck Hutchinson
Technical Editor: Jay Thrash
Editorial Manager: Jodi Jensen
Senior Project Editor: Sara Shlaer
Editorial Assistant: Annie Sullivan
Marketing
Marketing Manager: Lorna Mein
Marketing Assistant: Polly Thomas
Rob Napier is a builder of tree houses, hiker, and proud father. He began developing for the Mac in 2005, and picked up iPhone development when the first SDK was released, working on products such as The Daily, PandoraBoy, and Cisco Mobile. He is a major contributor to Stack Overflow and maintains the Cocoaphony blog (cocoaphony.com).
Mugunth Kumar is an independent iOS developer based in Singapore. He graduated in 2009 and holds a Masters degree from Nanyang Technological University, Singapore, majoring in Information Systems. He writes about mobile development, software usability, and iOS-related tutorials on his blog (blog.mugunthkumar.com). Prior to iOS development he worked for Fortune 500 companies GE and Honeywell as a software consultant on Windows and .NET platforms. His core areas of interest include programming methodologies (Object Oriented and Functional), mobile development and usability engineering. If he were not coding, he would probably be found at some exotic place capturing scenic photos of Mother Nature.
Jay Thrash is a veteran software developer who has spent the past three years designing and developing iOS applications. During his career, he developed a keen interest in the areas of user interaction and interface design.
Prior to settling down as an iOS developer, Jay has worked on a variety of platforms and applications, including flight simulators and web application development. He has also spent over six years in the PC and console gaming industry.
One more time, Rob thanks his family for their patience. He also thanks the Triangle Cocoaheads for their great ideas, inspiration, and support. Mugunth thanks his parents and friends for their support while writing this book. Thanks to Wiley, especially Craig Smith, for the continued support, encouragement, and nudging that it takes to get a book out the door. Thanks to Jay Thrash, Tom Dinse, and Chuck Hutchinson for keeping our words intelligible, and for keeping everything on schedule.
Chapter 1 The Brand New Stuff
Chapter 2 The World Is Flat: New UI Paradigms
iOS 7 gives your Apple devices a fresh user interface, but the beauty of iOS 7's user interface changes are not just skin deep. Like this book, iOS 7 is a major update that benefits both users and developers. We start the chapter discussing the new UI and how that new UI will impact your app. Moving on, we discuss the various SDK additions and the new IDE and Compiler, Xcode 5/LLVM 5.
iOS 7 also brings a wealth of new core features to the SDK that can help your app stand out. iOS 7 adds two new technologies, UIKit Dynamics and UIMotionEffects, that can help you add animations that were not easy to do with Quartz Core. Custom transitions between views that were possible only when using Storyboards are now extended to support transitions between any two view controllers. The built-in Calendar and Photos apps are good examples that use custom transitions to seamlessly provide a sense of where the user is within the app. TextKit, a much improved (easy-to-use) version of Core Text that is Objective-C based, is arguably the most important and interesting addition. Sprite Kit, Dynamic Text, tighter integration with MapKit, true multitasking for all applications, and much better Bluetooth LE support are other SDK additions, to name a few.
The new features don't stop there. Along with these new SDK features, iOS 7 has a new IDE, Xcode 5, which is rewritten completely using the Automatic Reference Counting (ARC) compiler. Xcode 5 is much faster and less prone to crashes. The new IDE also brings in an updated compiler, LLVM 5.
Apple has again made huge changes to the platform that are disruptive enough to make most of the apps on the already over crowded App Store obsolete. This means that it's a niche market once again for a variety of apps and it's as good to be an iOS developer as it was in 2008 when iOS SDK was launched.
Now let's delve deeper to gain an understanding of these new features, starting with the new UI.
The changes to iOS 7's UI are profound, not just “skinning.” The visual realism of the UI elements is muted and subdued while real world physics like motion realism is accentuated.
iOS 7 focuses on the following main themes: deference, clarity, and depth. Content is more important than chrome. As much as possible, apps now use the full screen to display content, and what was previously “chrome” is now translucent and shows muted, blurred content behind. All toolbars, navigation bars, and status bars also are now translucent. In addition to being translucent, they also blur and saturate the colors of the UI behind them, giving users a sense of depth, as you can see in Figure 1-1.
Figure 1-1: The area around the Timer tab of the Clock app shows a blurred black clock face behind it
Spatial depth is represented not just through the translucence of toolbars, navigation bars, and status bars, but throughout the UI. The home button on the multitasking bar is a great example of how spatial depth is shown in the iOS 7 UI. When you double tap the home button, you see app screenshots along with app icons. But that's not what is important. Pay close attention to the animation used: The whole screen “zooms out” to show all other running apps. Tapping an app icon “zooms” to that app. The calendar app also uses animation to provide a sense of spatial depth. Navigating from the year view to month view to date view uses a subtle transition that enhances the perception of spatial depth. Tapping a month zooms into the month, and tapping a year (from the month's screen) zooms out. Similarly, tapping an app icon launches the app by zooming in, not from the center of the screen as in prior iOS versions, but from the app icon's center. The reverse happens when you close the app. The app closes to the icon and not to the center of the screen, giving users a sense of where they are.
The new notification center, control center, and even some modal view controllers such as iPod's album list view controller also use blur effects to show what is “behind” them. Showing what is “behind” gives users a sense of where they are within your app.
The most interesting part of this new change is, as a developer, in most cases, you don't have to do any extra work to get these features working in your app if you have built your app using UIKit. You learn more about the new features of UIKit and how to design your app for iOS 7 in Chapter 2.
The iOS 7 SDK adds new classes that allow you to add realism in motion to your own user interface. You can add realistic motion to any object that conforms to the UIDynamicItem protocol. Starting with iOS 7, all UIViews conform to this protocol, which means that you can add realistic motion to any of the UIView subclasses (including UIControl) in your application.
Implementing physics like realistic motion was possible prior to iOS 7 using animation methods in the QuartzCore.framework. But the new APIs in iOS 7's UIKit makes this task much easier. What makes implementing realistic motion in iOS 7 easier is that you specify the UIKit's dynamic behavior in a declarative fashion while QuartzCore.framework is intrinsically imperative. You do this by “attaching” dynamic behaviors to your UIViews (or one of its subclasses).
You implement realism in motion by adding a UIDynamicAnimator to a view and attaching one of the following dynamic behaviors, namely, UIAttachmentBehavior, UICollisionBehavior, UIGravityBehavior, UIPushBehavior, UISnapBehavior to the subviews of the view. The properties exposed by these behaviors can be used to customize and tweak the behavior. The dynamic animator takes care of the rest. As I said previously, the coding is more declarative and less imperative. You tell the UIDynamicAnimator what you want, and it does the right thing for you.
In addition to UIViews, UICollectionViewLayoutAttributes also conform to the UIDynamicItem protocol. That means you also can attach dynamic behaviors to collection view items. A good example of this in practice is the built-in Messages app. As you scroll up and down the message thread, you see a realistic bouncy motion between the chat bubbles. In fact, the Messages app no longer uses table views and uses collection views and dynamic behavior attached to its items.
UIMotionEffect is another new class added in iOS 7 that helps you add motion realism to your user interface. Using UIKit Dynamics, you simulated motion realism based on physics that you defined programatically. Using UIMotionEffect, you can simulate motion realism based on the device's motion. Anything that can be animated using a CAAnimation can be animated using UIMotionEffect. Whereas CAAnimation's animation is a function of time, UIMotionEffect's animation is a function of device motion.
You learn more about UIKit Dynamics and UIMotionEffects in Chapter 19. Chapter 5 covers applying UIKit Dynamics to your collection views like the Messages app.
Prior to iOS 7, custom transitions were available only for storyboard-created user interfaces. You normally create a subclass of UIStoryboardSegue and override the perform method to perform a transition. iOS 7 takes this concept to the next level by allowing any view controller you push using the method pushViewController:animated: to use your own custom animation. You do this by implementing the protocol UIViewControllerAnimatedTransitioning.
In Chapter 20, you learn how to create a transition using UIStoryboardSegue (the classical way) and the new way using UIViewControllerAnimatedTransitioning.
From iOS 4 to iOS 6, only selected categories of apps were allowed to run in the background. Examples include a location-based app that needs a user's location whenever it changes or a music player app that needs to stream and play back music in the background. In iOS 7, Apple finally allows all apps to run in the background. But unlike the desktop equivalent, apps don't truly run in the background. Instead, an app can register itself to be launched periodically so that it can fetch content in the background. A new UIBackgroundMode key, fetch, is introduced in iOS 7 to enable this capability.
Another interesting addition is the remote-notification background mode that allows an app to download or fetch new data when a remote notification (push notification) is received.
New multitasking modes are covered extensively in Chapter 9.
In addition, the bluetooth-central and bluetooth-peripheral background modes now support a new technology called State Preservation and Restoration. This technology is similar to the UIKit's equivalent by the same name. Bluetooth-related multitasking modes are covered in Chapter 13.
Text Kit is a fast, modern Unicode text layout engine built on top of Core Text. Whereas Core Text heavily depends on CoreFoundation.framework, Text Kit is more modern and uses Foundation.framework classes. This also means that Text Kit is ARC (Automatic Reference Counting) friendly, unlike Core Text. Prior to iOS 7, most of the UIKit elements that render text—namely, UILabel, UITextView, and UITextField—used WebKit. Apple rewrote these classes and built WebKit on top of Text Kit, which means that Text Kit is a first-class citizen in UIKit. This means you can and you should use TextKit for all text rendering. Text Kit centers around three classes—NSTextStorage, NSLayoutManager, and NSTextContainer—in addition to the extensions to NSAttributedString. There is no separate framework for TextKit per se. The related classes and extention methods are added to UIKit.framework and Foundation.framework. You learn about Text Kit in Chapter 21.
With iOS 7, users can set how big or small the size of text should be. Almost all built-in apps respect this setting and dynamically change the size of the text based on the user's preference. Note that increasing text size doesn't always make the font's point size bigger. When the text size setting is set to values that might render smaller point size text illegible, iOS 7 automatically makes the text bolder. By incorporating the Dynamic Type feature into your app, you can also dynamically change the size of text based on the Text Size setting on the iOS Settings app. There is one downside to Dynamic Type in iOS 7: It doesn't support custom fonts as of iOS 7. You learn about Dynamic Type in Chapter 21.
iOS 7 adds even tighter integration with Apple Maps. You can now show 3D maps using the MKMapView object. If you are a mapping provider, you can use the same MKMapView control but provide your own map tiles to replace the built-in tiles. Additionally, you can use MKDirections to show directions right on the map without exiting your app.
SpriteKit is Apple's answer to cocos2d and box2d. SpriteKit provides a clean wrapper around OpenGL, much like QuartzCore.framework. Whereas QuartzCore.framework is predominantly used for UI animation, SpriteKit is more geared toward making games that simulate 3D (aka 2.5D games). SpriteKit is not covered in this edition of the book.
Another important change along with iOS 7 is Xcode 5 and the new LLVM 5 compiler. LLVM 5 has both user-facing features and performance features. LLVM 5 fully supports generating armv7s and arm64 instruction set; this means that your app will run faster on iPhone 5s and the latest iPad Air just by recompiling with the new LLVM 5 compiler.
On the C++ side, LLVM 5 now fully supports the C++ 11 standard and uses the new libc++ library instead of the old gnuc++ library.
On the Objective-C side, LLVM 5 adds new compiler warnings and enables some already-existing warnings by default. For example, the compiler notifies you of dead code—code that cannot be reached from anywhere else.
Arguably the most important addition is the treatment of enums as first-class citizens. Enums are proper types, and LLVM 5 shows a warning when you attempt a conversion from one enumeration type to another.
LLVM also detects whether a selector you use is declared in the scope. If it is not declared, LLVM 5 now warns you.
The Objective-C language has two major enhancements this year. They are modules and some changes to Automatic Reference Counting.
Apple introduced modules, which are intended to replace #import statements. For more than 30 to 40 years, #import statements were used in C/C++, and they were great for including a third-party library or framework. Over the years, the size of C/C++ applications grew, and #import statements started having serious compilation complexities. Every single .m file can potentially have several thousand lines of code just because of a few import statements, and some of these imports are, at times, repeated over many files. For example, consider #import <UIKit/UIKit.h> or #import <Foundation/Foundation.h>.
The problem was that whenever you modify a file, the compiler has to compile that file and all the code included by that file. This clearly increased the compilation time to O(S × H), where S is the number of source code files and H is the number of included header files. To circumvent this problem, some seasoned developers used to write forward declarations in the header files and import statements in the implementation files and add often-used header files into the precompiled header files. This approach solved the problem to some extent, probably by reducing the compilation time. But sometimes, adding not-so-commonly used header files to precompiled header files causes namespace pollution, and a badly written framework (that defines a class or a macro without a prefix) can get overwritten by some other class in another badly written framework.
To solve all these issues, Apple introduced modules. Modules encapsulate a framework and import statements into your code semantically instead of copying and pasting the content of the framework into your code.
Modules can reduce the compilation complexity from O(S × H) to O(S + H), which means that no matter how many times you import a module, it gets compiled once. That means, S source files and H header files are compiled S + H times instead of S × H times. In fact, the H header files are precompiled into dynamic libraries (dylib) and will be directly linked automatically, therefore reducing the compile time from O(S × H) to just O(S).
Modules are supported only if you use the latest Xcode 5 with the latest LLVM 5 compiler. More importantly, modules are available only for the latest SDK, iOS 7. If your project still has to support iOS 6, you will probably have to wait. When you use modules to import built-in libraries, you see much-improved compilation speeds, especially on larger projects. All new projects created in Xcode 5 automatically use modules. When you open an existing project in Xcode 5, you can add module support by turning it on from the Build Settings tab. This setting is shown in Figure 1-2.
Figure 1-2: Xcode 5 showing the LLVM 5's Modules setting
Modules also eliminate the need to link the framework explicitly in your project by adding them from the Build Phases tab of the project's settings editor. However, modules on this version of Xcode/LLVM are supported only for built-in libraries. This might change in the near future (Read: iOS 8).
LLVM 5 has better detection of retain cycles and also can predict whether a weak variable can become nil before being captured within a block. But what is more interesting is the ARC integration with Core Foundation classes. In prior versions of LLVM, the compiler mandated that you should bridge the cast even if there is no change in ownership. With LLVM 5, this case is implicit. That means, when there is no ownership change, you no longer need to “bridge” the cast between a Core Foundation object and an equivalent Foundation object.
Core Foundation and improvements to ARC are explained in detail in Chapter 20.
Xcode 4 was an ambitious project at Apple. In 2011, Apple completely threw away the separate Xcode and Interface Builder in Xcode 3, something that had been around for almost a decade and integrated the capability to edit Interface Builder files right within Xcode. However, Xcode 4 was slow and often crashed a lot, including during some of the Worldwide Developers Conference (WWDC) sessions.
The main reason for Xcode 4's slow performance was that it was still using the old GCC compiler and used garbage collection (instead of ARC). Xcode 5 has few user-facing changes but is completely new from the ground up. It is compiled using LLVM 5 and rewritten using ARC, and that means it's more memory efficient and faster on your machine.
The first major change Xcode 5 brings up is a new nib file format that is easier to read. The format is still in XML but is more human friendly. What that means is, as a developer, you are able to fix merge conflicts in your XIB files much easier.
However, the new file format is not backward compatible with the older Xcode, but in most cases that shouldn't be a problem. You should ensure that all developers in your team use the latest Xcode. Xcode 4.6 cannot open the new file format.
Xcode 5 now has support for merging and switching Git branches right from Xcode. Xcode 5 also allows pushing and pulling commits from a remote repository right from the IDE. This means you will spend less time outside Xcode (in Terminal or a third-party Git client) and more time in Xcode.
Xcode 4 had integration with the iOS developer program portal and allowed you to create and download provisioning profiles automatically. Xcode 5 takes this integration to the next level by allowing you to sign in to Xcode with your Apple ID. Xcode 5 automatically knows the various teams you work with and brings them all into Xcode. You can even set the team to a project, and Xcode automatically creates the necessary provisioning profiles on the developer portal for you.
Xcode 5 adds a new feature called capabilities that allows you to set high-level Apple features such as turning on In-App Purchases, iCloud, or Game Center right from Xcode. Xcode now automatically downloads the necessary provisioning profiles based on the new App ID and even updates your Info.plist file if required.
Xcode's debug navigator now shows real-time memory, CPU usage, and energy usage of your application right within Xcode. You no longer have to launch Instruments and profile your app as often. The debug navigator also lets you launch Instruments with the CPU/Memory profiling tool right from Xcode. Figures 1-3 and 1-4 show the CPU and Memory report features in Xcode 5.
Figure 1-3: Xcode 5's debug navigator showing CPU usage of the currently running application
Figure 1-4: Xcode 5's debug navigator showing memory usage of the currently running application
Xcode 5 has an entirely revamped documentation browser complete with tabbed browsing. You can bookmark documentation pages (unfortunately no iCloud sync support for documentation bookmarks). The table of contents is now presented in a separate tab outside the documentation content.
Dash, a third-party application, is much better and faster than even Xcode 5's documentation browser. It's free from Mac App Store, and I highly recommend that you check it out. Dash works out of the box with the docsets installed with Xcode and also provides documentation for third-party libraries such as cocos2d.
Asset Catalogs provide a new way to group artwork you use in your application. An Asset Catalog contains image sets (the images and resources you use within your application), app icons, and launch images. These launch images, app icons, and image sets are grouped based on the device they're designed for.
Asset Catalogs are mostly an Xcode feature, so that means you can use it even if your app needs to be supported on iOS 6. On iOS 6, Xcode ensures that UIImage's imageNamed: method will return the correct image within the catalog. On iOS 7, Xcode 5 compiles your Asset Catalog into a runtime binary (.car file) that reduces the time it takes for your app to download.
Asset Catalogs also provide an option to create stretchable images by allowing you to specify a resizable area within your image. All you have to do is select an image set within an Asset Catalog and click the Start Slicing button on top of your image. Adjust the slicing handle to specify the resizable area. You can choose to resize only vertically, only horizontally, or both.
Creating resizable areas (see Figure 1-5) within an Asset Catalog is, however, available only for projects with iOS 7 and higher as deployment target.
Figure 1-5: Resizable areas within an Image set in an Asset Catalog
Xcode 5 makes writing unit test cases a first-class citizen. All new projects created in Xcode 5 automatically include a new testing framework called XCTest.framework that supposedly replaces OCUnit (SenTestingKit.framework). SenTestingKit.framework is still shipped with Xcode 5, and Xcode 5 has an option to automatically migrate your test cases from OCUnit to XCTest. The advantages are easy testing with command-line tools such as xcodebuild. Xcode also adds a new navigator called the test navigator along with the seven other navigators in the prior version of Xcode. The test navigator shows the results of running the test cases you have written.
You can create a new type of breakpoint to stop the program execution when a test fails. It is illustrated in Figure 1-6. You can add this breakpoint from the breakpoints navigator.
Figure 1-6: Adding a test failure breakpoint