iOS 5 Programming Pushing the Limits - Rob Napier - E-Book

iOS 5 Programming Pushing the Limits E-Book

Rob Napier

0,0
27,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Open the door to endless new app development possibilities Pushing the Limits with iOS 5 Programming is an expert guide for developers aiming to create unique applications for Apple's iPad 2, iPhone, and the iPod Touch, which includes the latest version of the Apple iPhone SDK, iOS 5. This text goes beyond the basics to keep you ahead of the technology curve and spark your innovative nature to create seamless, functional, and fun apps. With a focus on advanced techniques for app development, you will learn to differentiate your apps from all the rest. With this must-have book, you'll explore advanced coverage of a variety of development topics, such as developing with deep Objective-C, while you learn to create amazing applications for Apple's iPad 2, iPhone, and iPod touch. Veteran mobile developers and authors guide you through maximizing your programs as they delve into topics not commonly found elsewhere. * Provides a solid foundation in the patterns of iOS * Shares tips for running on multiple platforms and best using security services * Discusses topics such as controlling multitasking, advanced text layout and more * Demonstrates how to think differently with blocks and functional programming * Teaches table view, performance, and money-making optimization * Eliminates common challenges with memory management and iOS information flow Pushing the Limits with iOS 5 Programming allows you to take on the future with confidence in your new, stand-out app design skills.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 626

Veröffentlichungsjahr: 2011

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Pushing the Limits with iOS 5 Programming: Advanced Application Development for Apple iPhone®, iPad®, and iPod® Touch

Table of Contents

Introduction
Who This Book Is For
What This Book Covers
How This Book Is Structured
Part I: What’s New?
Part II: Getting the Most Out of Everyday Tools
Part III: The Right Tool for the Job
Part IV: Pushing the Limits
What You Need to Use This Book
Finding Apple Documentation
Source Code
Part I: What’s New?
Chapter 1: The Brand New Stuff
The History of iOS
What’s New
iCloud
LLVM 3.0 Compiler
Automatic Reference Counting
Storyboards—Draw Your Flow
UIKit Customization—Appearance Proxy
Twitter Framework and Accounts Framework
Other New Features
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 2: Getting Comfortable with Xcode 4
Getting to Know the New User Interface
Tabbed Editor
Changes to Key Bindings
Project Settings Editor
Integrated Version Control
Workspaces
All in One Window
Navigating the Navigators
Project Navigator
Symbol Navigator
Search Navigator
Issue Navigator
Debug Navigator
Breakpoint Navigator
Log Navigator
Help from Your Assistant
Integrated Interface Builder
Interface Builder Panels
LLVM Compiler 3.0: A Tryst with the Brain
The Clang Front End
I’m a Bug! Fix Me
Git Your Versions Here
Integrated Git Version Control System
Versions Editor
Git Best Practices
Schemes
Why Schemes?
Think of Schemes as Implementing Your Intentions
Creating a Scheme
Sharing Your Schemes
Build Configurations You Can Comment
Creating an xcconfig File
Refactoring the Build Configuration File
Xcode 4 Organizer
Automatic Device Provisioning
Viewing Crash Logs and Console NSLog Statements
Viewing Applications’ Sandbox Data
Managing Repositories
Accessing Your Application Archives
Viewing Objective-C and SDK Documentation
Summary
Further Reading
Apple Documentation
Blogs
Web Resources
Books
Part II: Getting the Most Out of Everyday Tools
Chapter 3: Everyday Objective-C
Naming Conventions
Automatic Reference Counting
Properties
Property Attributes
Property Best Practices
Private Ivars
Accessors
Categories and Extensions
+load
Category Data using Associative References
Category Data using the Flyweight Pattern
Class Extensions
Formal and Informal Protocols
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 4: Hold On Loosely: Cocoa Design Patterns
Understanding Model-View-Controller
Using Model Classes
Using View Classes
Using Controller Classes
Understanding Delegates and Data Sources
Working with the Command Pattern
Using Target-Action
Using Method Signatures and Invocations
Using Trampolines
Using Undo
Working with the Observer Pattern
Working with the Singleton Pattern
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 5: Getting Table Views Right
UITableView Class Hierarchy
Understanding Table Views
UITableViewController
UITableViewCell
Speed Up Your Tables
Custom Nonrepeating Cells
Advanced Table Views
Animating a UITableView
Table View Best Practices: Writing Clean Code with Lean Controllers
Storyboards
Getting Started with Storyboards
Segues
Building Table Views with Storyboard
Custom Transitions
Customizing Your Views Using UIAppearance Protocol
Summary
Further Reading
Apple Documentation
WWDC Videos
Other Resources
Chapter 6: Better Drawing
iOS’s Many Drawing Systems
UIKit and the View Drawing Cycle
View Drawing versus View Layout
Custom View Drawing
Drawing with UIKit
Paths
Understanding Coordinates
Resizing and contentMode
Transforms
Drawing with Core Graphics
Mixing UIKit and Core Graphics
Managing Graphics Contexts
Optimizing UIView Drawing
Avoid Drawing
Caching and Background Drawing
Custom Drawing Versus Prerendering
Pixel Alignment and Blurry Text
Alpha, Opaque, Hidden
CGLayer
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 7: Layers Like an Onion: Core Animation
View Animations
Managing User Interaction
Drawing with Layers
Setting Contents Directly
Implementing Display
Custom Drawing
Drawing in Your Own Context
Moving Things Around
Implicit Animations
Explicit Animations
Model and Presentation
A Few Words on Timings
Into the Third Dimension
Decorating Your Layers
Auto-animate with Actions
Animating Custom Properties
Core Animation and Threads
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 8: Tackling Those Pesky Errors
Error Handling Patterns
Assertions
Exceptions
Catching and Reporting Crashes
Errors and NSError
Error Localization
Error Recovery Attempter
Logs
Logging Sensitive Information
Getting Your Logs
Summary
Further Reading
Apple Documentation
Other Resources
Part III: The Right Tool for the Job
Chapter 9: Controlling Multitasking
Best Practices for Backgrounding: With Great Power Comes Great Responsibility
Understanding Run Loops
Threading
Developing Operation-Centric Multitasking
Multitasking with Grand Central Dispatch
Creating Synchronization Points with Dispatch Barriers
Queue Targets and Priority
New in iOS 5
Summary
Further Reading
Apple Documentation
WWDC Sessions
Other Resources
Chapter 10: REST for the Weary
The REST Philosophy
Choosing Your Data Exchange Format
Parsing XML on iOS
Parsing JSON on iOS
XML Versus JSON
Model Versioning
A Hypothetical Web Service
Important Reminders
RESTEngine Architecture (iHotelApp Sample Code)
Creating the RESTEngine
Authenticating Your API Calls with Access Tokens
Canceling Requests
Request Responses
Key Coding JSONs
List Versus Detail JSON Objects
Nested JSON Objects
Less Is More
Error Handling
Localization
Handling Additional Formats Using Category Classes
Tips to Improve Performance on iOS
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 11: Batten the Hatches with Security Services
Understanding the iOS Sandbox
Securing Network Communications
How Certificates Work
Checking Certificate Validity
Determining Certificate Trust
Employing File Protection
Using Keychains
Sharing Data with Access Groups
Using Encryption
Overview of AES
Converting Passwords to Keys with PBKDF2
Applying PKCS7 Padding
Selecting the Mode and the Initialization Vector (IV)
Performing One-Shot Encryption
Improving CommonCrypto Performance
Combining Encryption and Compression
Summary
Further Reading
Apple Documentation
WWDC Sessions
Other Resources
Chapter 12: Running on Multiple iPlatforms and iDevices
Developing for Multiple Platforms
Configurable Target Settings: Base SDK Versus Deployment Target
Considerations for Multiple SDK Support:Frameworks, Classes, and Methods
Checking the Availability of Frameworks, Classes, and Methods
Detecting Device Capabilities
Detecting Devices and Assuming Capabilities
Detecting Hardware and Sensors
In App Email and SMS
Checking Multitasking Awareness
Obtaining the UIDevice+Additions Category
UIRequiredDeviceCapabilities
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 13: Internationalization and Localization
What is Localization?
Localizing Strings
Auditing for Nonlocalized Strings
Formatting Numbers and Dates
Localizing Nib Files
Summary
Further Reading
Apple Documentation
Chapter 14: Selling Past the Sale with In App Purchases
Before You Start
In App Purchase Products
Prohibited Items
Rethinking Your Business Model
Setting Up Products on iTunes Connect
Step 1: Create a New App ID for Your App
Step 2: Generate Provisioning Profiles
Step 3: Create the App’s Product Entry
Step 4: Create the In App Purchase Product Entries
Step 5: Generating the Shared Secret
Step 6: Creating Test User Accounts
In App Purchase Implementation
Introduction to MKStoreKit
Why MKStoreKit?
Design of MKStoreKit
Customizing MKStoreKit
Making the Purchase
Testing Your In App Purchase
Troubleshooting
Invalid Product IDs
Cannot Connect to iTunes Store
You Have Already Purchased This Product, but It’s Still Not Downloaded
Summary
Further Reading
Apple Documentation
Blogs
Other Resources
Part IV: Pushing the Limits
Chapter 15: Cocoa’s Biggest Trick: Key-Value Coding and Observing
Key-Value Coding
Setting Values with KVC
Traversing Properties
KVC and Collections
KVC and Dictionaries
KVC and Nonobjects
Higher-Order Messaging with KVC
Collection Operators
Key-Value Observing
KVO and Collections
How Is KVO Implemented?
KVO Tradeoffs
Summary
Further Reading
Apple Documentation
Chapter 16: Think Different: Blocks and Functional Programming
What Is a Block?
Why Use Functional Programming?
A ‘Functional’ UIAlertView
Declaring a Block
Scope of Variables
Stack Versus Heap
Implementing a Block
Blocks-based UIAlertView
Blocks-based RESTEngine
Blocks and Concurrency
Dispatch Queues in GCD
NSOperationQueue Versus GCD Dispatch Queue
Block-based Cocoa Methods
UIView Animations using Blocks
Presenting and Dismissing View Controllers
TweetComposer Versus In App Email/SMS
Dictionary Enumeration Using NSDictionary enumerateWithBlock
Looking for Block-based Methods
Supported Platforms
Summary
Further Reading
Apple Documentation
Blogs
Source Code References
Chapter 17: Going Offline
Reasons for Going Offline
Strategies for Caching
Methods for Storing Your Cache
Cache Versioning
AppCache Architecture
Cache Versioning
Invalidating the Cache
Creating an In-Memory Cache
Designing the AppCache
Handling Memory Warnings
Handling Termination and Enter Background Notifications
Caching Images
Components of ImageCache
Using iCloud
Managing Document and Key-Value Data Storage on iCloud
Understanding the iCloud Data Store
Summary
Further Reading
Apple Documentation
Books
Other Resources
Chapter 18: Fancy Text Layout
The Normal Stuff: Fields, Views, and Labels
Web Views for Rich Text
Displaying and Accessing HTML in a Web View
Responding to User Interaction
Drawing Web Views in Scroll and Table Views
Rich Editing with Web Views
Core Text
Understanding Bold, Italic, and Underline
Attributed Strings
Paragraph Styles
Simple Layout with CTFramesetter
Creating Frames for Noncontiguous Paths
Typesetters, Lines, Runs, and Glyphs
Drawing Text Along a Curve
Comparison of Rich Text Options
Third-Party Options
NSAttributedString-Additions-for-HTML
CoreTextWrapper
OmniUI
Summary
Further Reading
Apple Documentation
WWDC Sessions
Other Resources
Chapter 19: Building a (Core) Foundation
Core Foundation Types
Naming and Memory Management
Allocators
Introspection
Strings and Data
Constant Strings
Creating Strings
Converting to C Strings
Other String Operations
Backing Storage for Strings
CFData
Collections
CFArray
CFDictionary
CFSet, CFBag
Other Collections
Callbacks
Toll-free Bridging
Summary
Further Reading
Apple Documentation
Other Resources
Chapter 20: Deep Objective-C
Understanding Classes and Objects
Working with Methods and Properties
How Message Passing Really Works
Dynamic Implementations
Fast Forwarding
Normal Forwarding
Forwarding Failure
The Flavors of objc_msgSend
Method Swizzling
ISA Swizzling
Method Swizzling Versus ISA Swizzling
Summary
Further Reading
Apple Documentation
Other Resources

Pushing the Limits with iOS 5 Programming

Advanced Application Development for Apple iPhone®, iPad®, and iPod® Touch

Rob Napier and Mugunth Kumar

This edition first published 2012

© 2012 John Wiley and Sons, Ltd.

Registered office

John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, 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 John Wiley & Sons, Ltd. logo are trademarks or registered trademarks of John Wiley and Sons, 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 are trademarks of Apple Computer, 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. This book is not endorsed by Apple Computer, Inc.

A catalogue record for this book is available from the British Library.

ISBN 978-1-119-96132-1 (paperback); ISBN 978-1-119-96158-1 (ebook); 978-1-119-96159-8 (ebook); 978-1-119-96160-4 (ebook)

Set in 9.5/12 Myriad Pro Regular by Wiley Composition Services

Printed in the United States by Bind-Rite

Dedication

To Neverwood. Thanks for your patience.Rob

To my mother who shaped the first twenty years of my lifeMugunth

Publisher’s Acknowledgements

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

Acquisitions Editor: Chris Katsaropolous

Assistant Editor: Ellie Scott

Development Editor: Tom Dinse

Copy Editor: Maryann Steinhart

Technical Editor: Mithilesh Kumar

Editorial Manager: Jodi Jensen

Senior Project Editor: Sara Shlaer

Editorial Assistant: Leslie Saxman

Marketing

Associate Marketing Director: Louise Breinholt

Marketing Executive: Kate Parrett

Composition Services

Compositor: Wiley Indianapolis Composition Services

Proofreaders: Laura Albert, Lindsay Amones, Melissa D. Buddendeck, Melissa Cossell

Indexer: Potomac Indexing, LLC

About the Authors

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.

About the Technical Editor

Mithilesh Kumar is a software engineer with a passion for user interface design, Internet protocols, and virtual worlds. He likes to prototype and build applications for iOS and Mac OS X platforms. He has extensive experience in developing UI and core components for telephony clients capable of voice, video, instant messaging, presence, and voicemail.

Mithilesh graduated with a Masters degree in Computer Science from Virginia Tech with emphasis on Human-Computer Interaction. While at graduate school, he co-authored several research papers in the area of user interfaces, computer graphics and network protocols.

Authors’ Acknowledgements

Rob thanks his family for giving up many evenings that he spent in the basement writing, hacking, and otherwise failing to come upstairs. Mugunth thanks his parents and friends for their support while writing this book. Thanks to Wiley for making this book possible. It went extremely well, particularly due to Sara Shlaer’s continual guiding hand. Thanks to Mithilesh Kumar who made sure what we said was true, and Tom Dinse who made sure that it was intelligible. Thanks to Chris Katsaropoulos for first reaching out and getting this project rolling. Thanks to the Apple engineers who answer questions on development forums on all those still-under-NDA issues, and the whole iOS developer community who share so much. And special thanks to Steve Jobs for building toys we could build a career around.

Part I: What’s New?

Chapter 1 The Brand New Stuff

Chapter 2 Getting Comfortable with Xcode 4

Chapter 1: The Brand New Stuff

In 2007, the late Steve Jobs took the stage at Macworld and proclaimed that software running on iPhone was at least five years ahead of the competition. Since its initial release, Apple has been iterating the operating system year after year, and has even added two new devices, the iPad and Apple TV, to the list of products capable of running it. As the operating system was customized to run on more devices than just the iPhone, it was rebranded as iOS. Today, it’s almost 5 years old, and iOS 5 is easily the biggest update to iOS since the original launch, possibly making the software five years ahead of the competition again.

This book is about programming with iOS 5. Targeting intermediate to advanced iOS developers, this book, unlike most others, covers advanced topics of iOS development. Rather than learning about frameworks and the features available on the iOS SDK, you learn about how to make the best use of those features to help push your apps to the next level. This chapter briefly describes the new features covered in detail in the book and tells you the chapters in which they are discussed.

The History of iOS

The second version, iPhone OS 2, was the first to have a public SDK. From then on, with every release of the operating system, Apple introduced several major features and a lot more minor API changes. This section briefly describes the history of the iOS. The remaining sections in the chapter provide an overview of what’s new in iOS 5.

iPhone OS 3 brought Core Data from Mac to iPhone. Other additions include Apple Push Notification Service, External Accessory Kit, In App Purchases through the StoreKit.framework, in app email sheets, the MapKit.framework that allows developers to embed Google Maps into their apps, read-only access to the iPod library, and keychain data sharing. OS 3.1 added video editor support, a minor update. iPhone OS 3.2 added Core Text and gesture recognizers, file sharing, and PDF generation support, another minor (yet so major) update. OS 3.2 also added a whole new product, iPad, support for developing apps that run on iPad, and universal apps that run on iPad (3.2) and iPhone (3.1.3). 3.2 was iPad only and didn’t run on iPhone or iPod touch devices.

iPhone OS 4 (rebranded as iOS 4) introduced much-awaited multitasking support, local notifications, read-only access to calendar (Event Kit framework, EventKit.framework), blocks, Grand Central Dispatch (GCD), in app message composer sheets (SMS), and Retina display support. This version was iPhone only and didn’t support developing apps for iPad. A minor update, iOS 4.2, unified iPhone and iPad operating systems.

What’s New

iOS 5 introduces several important features like iCloud, Automatic Reference Counting (ARC), Storyboards, built-in Twitter framework, and several other minor features. The next few sections introduce you to the key features added to iOS 5 and the chapters in which they are discussed in detail and where I provide guidance about how to push your apps to the next level.

iCloud

iCloud is a new cloud service provided by Apple. iCloud differs from competing similar offerings in that it’s more a cloud-based service than cloud-based storage. Developers have been using third-party services for synchronizing data across multiple devices. Dropbox is the most popular of these services; however, even Dropbox API version 0 (the latest version as of this writing), doesn’t support conflict handling, something that’s critical for data integrity. While Dropbox has conflict resolution, it’s not exposed to developers via their API. iCloud, on the other hand, supports file storage and has conflict resolution built into the iOS 5 SDK.

iCloud also supports storing key-value data on the cloud, which is good enough for apps that need settings and other similar data to be kept in sync.

iCloud is not just a hard disk on the cloud. Think of iCloud as a cloud-based service that just happens to support data storage.

iOS 5 adds several new APIs for adding iCloud support:

■ UIDocument (very similar to its kin, NSDocument, on Mac)

■ UIManagedDocument, for managing your Core Data storage

■ Additions to NSFileManager to move and restore files from iCloud

iCloud is covered in detail in Chapter 17.

LLVM 3.0 Compiler

LLVM (Low Level Virtual Machine) is a new compiler project partly funded by Apple. While technically not a part of iOS 5, developers should be equipped with the knowledge of the new features available in LLVM. Improved auto complete and speedier compilation are just a part of LLVM’s new features. In Chapter 2 you learn about the features of LLVM and how LLVM augments Xcode 4’s features.

Automatic Reference Counting

Another important feature of iOS 5 is Automatic Reference Counting (ARC). It is a compiler-level feature provided by the new LLVM compiler. This means that you can use it without increasing the minimum SDK support to iOS 5. ARC can be used in apps targeting iOS 4 onward, and Xcode 4.2 also provides support for migrating your code to use ARC using the Convert to Objective-C ARC tool. With the new LLVM compiler slowly becoming mainstream, ARC will supercede the current retain/release memory management.

Automatic Reference Counting is notlike garbage collection offered on Mac OS X from version 10.5 (Leopard). Garbage collection is automatic memory management. This means that developers don’t have to write a matching release for every retain statement. The compiler automatically inserts them for you.

ARC adds two new lifetime qualifiers—strong and weak—and it also imposes new rules, such as that you can no longer invoke release, retain on any object. This applies to custom dealloc methods as well. When using ARC, your custom dealloc methods should only release resources (files or ports) and not instance variables.

ARC is covered in detail in Chapter 3.

Storyboards—Draw Your Flow

Storyboards is a new way to design your user interface. Prior to iOS 5 you used Interface Builder nib files to define your UI one view controller at a time. With Storyboards, you can define in one file the complete UI flow of your app, including interaction among the different view controllers.

You can use Storyboards to define all view controllers in your app. You don’t have to create multiple Storyboards or worry about performance. The Interface Builder build tool automatically splits your storyboard file into parts and loads it individually at runtime without affecting performance.

On iOS 5, storyboards replace MainWindow.xib nib file (and possibly every other view controller’s nib file). The new project template in Xcode 4.2 helps in creating storyboards. You can also add a storyboard to your old projects and optionally make it the main storyboard by adding an entry to the Info.plist file.

Storyboards, unlike ARC, is an iOS 5-specific feature, and using Storyboards means that you need to raise your minimum supported OS to iOS 5.

You will learn more about storyboards in Chapter 5.

UIKit Customization—Appearance Proxy

Apple (and even Microsoft) has always been against UI customization, or theming. Its reasoning is that theming makes it difficult for users to understand the user interface. The Web, on the other hand, has made a huge revolution on this front and this has had an effect on the latest release of iOS as well. Beginning with iOS 5, some native apps like Reminders get some rich customization. With iOS 5, most properties of UIKit elements can be customized. This includes backgroundColor, tintColor,and a lot more. Customization is supported by a UIView subclass if it implements the UIAppearance protocol. The protocol also allows customization based on the contained view. For example, you can have a different tint when a custom view of yours is within a navigation bar.

Chapter 5 covers UI customization.

Twitter Framework and Accounts Framework

iOS 5 integrates Twitter experience right into the OS. This means sending a tweet from your app is as easy as sending an email using an in app email sheet. The framework also handles authentication for you, which means you no longer need to do the oAuth/xAuth authentication yourself. Twitter framework on iOS 5 integrates with Accounts framework to provide account authentication. As of this writing, Twitter is the only third-party authentication system supported natively on iOS 5. But, by looking at the decoupled design of Twitter framework and Accounts framework, there is a possibility that additional services might be introduced later on. While there are some advantages of using these frameworks, it’s still an iOS 5-specific feature, which means that using it requires you to limit your app to devices running iOS 5 and later. Additionally, when you send out a tweet through iOS, you will not be able to customize the sender (via text). As such, your tweet will be sent as “via iOS.” (See Figure 1-1.)

© Twitter 2011

Figure 1-1 Screenshot from Twitter.com showing the “via” text

When you create a new application on Twitter, you can name it so when you tweet using this application’s credentials, its name shows up in the “via” text. The built-in Twitter.framework on iOS 5 doesn’t allow setting this text, so if you are considering using Twitter for increasing your brand’s reach, you may have to evaluate branding versus ease of development.

Adding Twitter experience to your app with the new Twitter.Framework is as easy as sending an in app email. This differs from an app email in one aspect. Instead of providing a delegate callback, the TWTweetComposeViewController of Twitter.Framework provides a completionHandler. Chapter 16 shows you an example of this in action.

Other New Features

In addition to the “big” features discussed in the preceding sections, iOS 5 also adds several other features, including dedicated support for magazine apps, a native image processing library, AirPlay mirroring support, and new controls added to UIKit.framework.

Newsstand Kit

Newspaper or magazine apps can make use of the NewsstandKit.framework to deliver digital content. Although it was technically possible to do something similar with iOS 4, iOS 5 introduces several new APIs to enable content for the latest release to be downloaded in the background. Additionally it also enables publishers to provide a cover art image (front cover) for their magazine instead of an icon. Apps developed using this framework appear within the Newsstand app and display the cover art instead of the app icon.

Core Image for Image Processing

Camera apps can use features in Core Image to apply image processing filters. The classes CIImage and CIFilter add basic image-editing functions like cropping, rotation (affine transform), and color inversion, to advanced features like gamma correction, white point adjustment, false color, sepia toning, temperature and tint correction, and many more that would be present in any entry-level image editor. This feature of iOS 5 will be tremendously useful for camera-enhancement apps that compete with apps like Instagram or Camera+. iPhone camera is already the most popular camera on Flickr. This framework will take it even further.

Core Image for Feature Detection

Core Image has another important element: feature detection. At WWDC 2011, Apple demonstrated a feature of Photo Booth that tracks the location of a face and adorns it with birds circling the head. With Core Image, you can add such features with very little programming effort. The class CIDetector has a convenient featuresInImage: method that returns a list of CIFeature objects detected in the given image.

Core Image is discussed in Chapter 6.

Other Minor Enhancements

iOS 5 adds many other minor enhancements like AirPlay video support, mirroring (which can be disabled by your app if you are showing protected content); better document support; improvements in data protection (Chapter 11); a new control, UIStepper; capability to add a password entry field to the UIAlertView just like the AppStore password prompt; a new UIPageViewController for creating page curl effects like iBooks; and much more. All these major and minor enhancements together make iOS 5 the biggest enhancement since its inception.

Summary

Adoption rates of iOS have always been way ahead of the competition. A couple of years ago, when iPhone OS 3.0 was launched, adoption rates were partly hindered on iPod touch because the upgrade cost $10. However, Apple soon made it free and adoption rates increased. Similarly, when Apple released iOS 4, the adoption rate was initially slow because of performance issues on older phones such as iPhone 3G and the original iPhone (and equivalent iPod touches). Some features—mainly multitasking—were also not available for older devices. Nevertheless, the latest iOS usually gets adopted on more than 90 percent of devices within the first two months of launch.

With iOS 5, adoption rates should be the fastest ever for the following reasons. First, the update is free for all devices, unlike iPhone OS 3. Second, unlike iOS 4, iOS 5 doesn’t make older devices (the iPhone 3GS) run slower. Finally, for end users, cleaner notifications, iTunes wi-fi sync, and iMessage are killer features that should accelerate iOS 5 adoption.

All this means that you should start using every iOS 5 feature as soon as possible to get your app to shine in all its glory. Features like iCloud and UIKit customizations alone should be reason enough to update your apps to iOS 5. That said, the next chapters start you on your iOS 5 journey.

Further Reading

Apple Documentation

The following documents are available in the iOS Developer Library at developer.apple.com or through the Xcode Documentation and API Reference.

iCloud

What’s New in iOS 5

Twitter Framework

Accounts Framework

Other Resources

How is a file conflict detected using the API - Dropbox forums http://forums.dropbox.com/topic.php?id=40492

Chapter 2: Getting Comfortable with Xcode 4

Apple officially announced Xcode 4 at WWDC 2010 (June 2010), and the beta version was available to attendees. It was in beta for quite a while (around 9 months) and a Gold Master was made available through iOS/Mac developer center in February 2011. Weeks later, in March, Xcode 4 was officially released and developers who subscribe to the iOS or Mac developer programs were able to get it for free. Others were able to buy it from the Mac App Store.

Xcode 4 is a completely rewritten IDE (integrated development environment) replacing Xcode 3. The major features include, but are not limited to, single window editing, navigators, integrated Interface Builder, an integrated Git version control system, and schemes (a new way to configure and share build settings in your product). You learn in detail about every major feature in this chapter.

Xcode 4 features are not just skin deep—they come with some huge compiler-level changes as well. The LLVM compiler is the new brain behind Xcode. Apple made LLVM-GCC the default compiler in the original version of Xcode. Beginning with Xcode 4.0 and in the version that is released with iOS 5 (Xcode 4.2), LLVM 3.0 is the default compiler; it uses Clang as its front end. Using Clang as the front end over GCC has several advantages, and several new features of Xcode 4 were added because of this change. Because Apple is moving from GCC to LLVM, you should know how to harness the power of the new compiler to increase your coding and debugging speed, and how to use the IDE to be more productive. The most important feature of the LLVM compiler is better and faster compilation with the Clang front end, which provides better code completion support.

This chapter covers the important features of the IDE, the new features offered by the LLVM compiler, the built-in integrated version control system, schemes (new to Xcode 4), writing readable and commentable project configuration files, and finally, the features of the new Xcode 4 Organizer.

Getting to Know the New User Interface

Xcode 4 features a whole new iTunes-like user interface (UI). The toolbar is gone in favor of iTunes-like Play/Stop buttons. The build setting chooser is gone in favor of the new schemes selector. There’s a new LED-like status display similar to iTunes. Developers who are used to Xcode 3 will feel at home once they know where things are, what has been removed, and what has been superseded. You’ll welcome the new additions and actually be more productive than ever. This section helps you bridge the gap between Xcode 3 and Xcode 4.

This section covers the six most important changes to Xcode 4. The first important change is the new navigators. There are seven navigators that can be accessed by clicking the buttons highlighted in Figure 2-1. They can also be accessed via the shortcut keys Cmd-1 to Cmd-7.

Figure 2-1 The Xcode navigator items

The same navigators can be accessed from the Xcode’s View menu item as shown in Figure 2-2.

Figure 2-2 Accessing the new navigators from the menu bar

The first view in the Navigators area is the project navigator. Previously, this was the Groups and Files list. From the Groups and Files list you were able to add frameworks and edit the target’s properties. With Xcode 4, however, this functionality is moved to the project and build settings editor view. The Xcode 4 workspace pane can now edit more types of files than just Objective-C or property list files, and the project and build settings editor just happens to be one such editor. You can access the build settings editor by selecting the project file from the project navigator. Figure 2-3 shows Xcode 4 project navigator.

Figure 2-3 Xcode project navigator view

The subsequent navigators are Symbol, Search, Issue, Debug, Breakpoint, and Log. You look at them in detail later in this chapter.

Tabbed Editor

The second major change is the new tabbed editor. Unlike its predecessor, Xcode 4 supports opening multiple tabs within the same window. This means that you will spend less time searching for the window that displays your source file. Figure 2-4 shows Xcode 4’s tabbed editor in action.

Figure 2-4 Xcode 4 window showing a several opened tabs

The tabbed editor in Xcode 4 behaves differently from tabbed editors in, for example, Eclipse, Visual Studio, or TextMate. Think of Xcode 4’s tabs as virtual workspaces instead of just file editors. The navigator pane’s file selection and search criteria are preserved when you switch back and forth between tabs. I recommend opening three to four tabs, each showing a related group of files. For example, you can use one tab to show your model classes, use another tab for your view controllers, a third tab for Interface Builder files, and maybe, if you use Core Data, use a fourth tab for showing Core Data-related files. Use tabs to make the workspace suit your thought process or workflow. Going to work on your Core Data files? Switch to the Core Data tab. Going to work on Interface Builder? Switch to the Interface Builder tab.

Changes to Key Bindings

The third major change is to key bindings. Xcode 4 has changed most of its keyboard shortcuts, which means you have to learn those quick shortcut keys again. Three commonly used shortcuts for debugging are changed to F6 (Step over), F7 (Step into), and F8 (Step out). Another commonly used shortcut that has been changed is for switching between header and source code counterparts. Xcode 3 used Cmd-Opt-Up Arrow; Xcode 4 uses Cmd-Ctrl-Up Arrow. The shortcut for Build and Run, which was Cmd-Return, is now Cmd-R.

For a good, comprehensive list of keyboard shortcuts, I recommend Cocoa Samurai’s list, available for download at http://cocoasamurai.blogspot.com/2011/03/xcode-4-keyboard-shortcuts-now.html, and another by The Pragmatic Studio, available at http://pragmaticstudio.com/media/Xcode4Shortcuts.pdf.

Project Settings Editor

The fourth major change is the new project settings editor. In Xcode 3 you normally edit your project settings by Cmd-clicking your target from the Groups and Files list and choosing Edit. This has been completely revamped and moved to the project settings editor. The project settings editor also allows you to edit your build settings and other commonly accessed functions like the NSZombieEnabled and GuardMalloc options. Furthermore, adding additional frameworks to your product and passing command line arguments are all now a part of this build settings panel of the project settings editor.

Integrated Version Control

The fifth major change is the supported integrated version control system. Xcode 3 supported Subversion (SVN), Perforce, and Concurrent Versions System (CVS) for versioning your source code. Xcode 4 removes support for Perforce and CVS and adds Git. Later in this chapter you learn how to get the best out of your version control system.

Workspaces

The sixth major change is the addition of workspaces to projects. In Xcode 3, the top level of your app is the project. In Xcode 4 you can create a workspace and add multiple projects within it. For example, if you are writing a Mac + iOS app, you can share a wealth of code. Instead of manually copying and pasting code, you can extract the common code into a separate static library project and add it to the workspace. The primary advantage of a workspace is implicit dependencies. This means that when you build your Mac app (or iOS app), Xcode 4 automatically detects that it’s dependent on your static library project and builds it first, without you explicitly requesting it to do so.

All in One Window

Unlike Xcode 3, Xcode 4 is a single window IDE like Eclipse or Visual Studio. Every file you use in your project can be opened without “switching” to it using Mac’s Exposé. With full screen editing in Lion, you will appreciate the single window IDE and find yourself spending less time switching or searching for a window.

The IDE, as you saw earlier in this chapter, consists of a set of navigators, a workspace area, and the utility area. There are seven navigators that replace the functionality of the Groups and Files view.

The workspace area is where you edit your files, which can be either source code or plist or even Interface Builder (IB) files. There are three different kinds of editors: the Standard editor that you use for editing files, the Assistant editor for editing files related to the current file in Standard editor, and a Versions editor that shows the version history of a file.

The Utility area is akin to the Inspector pane found on most other applications. Below the Utility area is the library from where you can drag user interface elements into your IB or code snippets into your source code. Let’s take a closer look at the different navigators available in Xcode 4.

Navigating the Navigators

Seven navigator panes are built into Xcode 4. These features were also present in Xcode 3 (in the Groups and Files view), but are presented in a more meaningful way in Xcode 4.

In Xcode 3, there used to be a single view—the Groups and Files view—where you did pretty much everything. You chose the file to edit, edited project settings, added frameworks, accessed breakpoints and debug logs, and a lot more all from the same view. Xcode 4 groups these actions into seven different navigators.

All navigators have a filter and scope box (shown in Figure 2-5) that can be accessed using Cmd-Opt-J. This shortcut puts the focus on the filter and scope box below the navigator from where you can search for a project file. The keyboard shortcut works for all navigators, so if you are in, say, the symbol navigator, you can use this to quickly filter symbols. The filter box might have additional buttons to restrict the scope, and sometimes (as in the debug navigator) it might be replaced with a UI that looks different but offers the same functionality.

You can press the shortcut key Cmd-Opt-J to quickly jump to the filter and scope box.

Navigators provide a clear separation of duties on the UI. For example, there is a dedicated navigator for breakpoints, a dedicated navigator for issues, and another for logs. Although it might be difficult to switch to the new, separate navigators, you will appreciate them once you get accustomed to them.

Some features, like the capability to create smart groups, were dropped probably because few people use them. However, if you have a project in Xcode 3 that uses smart groups, opening it in Xcode 4 and saving it doesn’t remove them from the project file. So when you open the project again on Xcode 3, you will still see your smart groups.

Project Navigator

The project navigator is equivalent to the Groups and Files view in Xcode 3. As its name suggests, the project navigator helps you locate your source code files, frameworks, and targets. Similar to Xcode 3, the project navigator also serves as a source code control UI. This means that when you add files to the project navigator, they are automatically added to your source control (if you use one) and the project navigator also updates the UI with the files’ source control status.

Figure 2-5 Xcode navigator showing the search and scope bar

Symbol Navigator

You can jump to the symbol navigator with the Cmd-2 shortcut. The symbol navigator makes it easy to locate a specific symbol or class in your project. The Clang front end of the LLVM compiler integrates well with Xcode 4 and has made it faster to browse through symbols in the project.

Search Navigator

The search navigator is functionally exactly the same as the Xcode 3’s Find and Replace feature. You can access this navigator with the traditional Cmd-Shift-F shortcut or the navigator shortcut Cmd-3.

Issue Navigator

When you build your project, compiler warnings, error messages, or analyzer warnings appear on the issue navigator. The issue navigator on Xcode 4 is clear of build log messages, unlike Xcode 3’s equivalent debug view. In Xcode 4, build logs are moved to a separate navigator called the log navigator, which maintains every build log in chronological order. You can access this using the navigator shortcut Cmd-4.

Debug Navigator

The debug panel in Xcode 3, which you access by pressing Cmd-Shift-Y, is equivalent to Xcode 4’s debug navigator. You can access the debug navigator in Xcode 4 using the navigator shortcut Cmd-5. The most important addition is the scope slider. Instead of the filter and scope search box present in other navigators, the debug navigator uses a scope slider. Drag the scope slider to customize your scope preference.

Breakpoint Navigator

The sixth navigator is the breakpoint navigator. On Xcode 3, this was managed in a separate window. The nifty addition here is the ability to quickly add a symbolic breakpoint or an exception breakpoint. You can access the breakpoint navigator using the shortcut Cmd-6.

A noteworthy feature of the breakpoint navigator is the ability to share your breakpoints with co-workers. From the breakpoint navigator, Cmd-Click the project file and click Share Breakpoints.

Log Navigator

On Xcode 3, logs can be either configured to either clear themselves for every build or continue to add to the current project log. On Xcode 4, this is no longer the case. With the log navigator, every build gets its own log entry and you can even search for entries in a log that was created several builds ago. You can access the log navigator using the shortcut Cmd-7.

Help from Your Assistant

Xcode 4 has three main editors, and they are akin to multiwindow document editing present in other competing IDEs. The two editors that augment Xcode 4’s Standard editor are the Assistant editor and the Versions editor. The best thing about the Assistant editor is that, when you turn in on, it intelligently knows the most relevant file to the file you are currently working with.

For example, when you are editing a Core Data model, turning on Assistant editor opens the corresponding Core Data’s model file. Similarly, when you are editing an Interface Builder file, it opens the corresponding header file.

A common action like adding an IBAction declaration in your header and coming back to the Interface Builder to connect it can be easily done within the same window using the Assistant editor.

Integrated Interface Builder

Prior to Xcode 4, Interface Builder was a standalone application, and the most common mistake a programmer would make was failing to sync Interface Builder and Xcode properly. For example, forgetting to save an Interface Builder connection could crash your app at runtime. Additionally, the very fact that there are two applications for writing iOS apps confuses developers coming from an Eclipse or Visual Studio background. Those difficulties are in the past because Xcode 4 integrates Interface Builder right into the main IDE, and it’s now very easy to sync your user interface with the controller code.

Interface Builder Panels

Interface Builder on Xcode 3 usually has multiple windows floating around. At a bare minimum, you have the main document window, the library panel, the inspector, and the actual user interface view. In Xcode 4, the library and inspector are brought into the utility area. The document window is docked to the left. Figure 2-6 shows a classical Interface Builder file open in Xcode 4.

Figure 2-6 Xcode 4 Interface Builder

The left pane now contains the objects in the Interface Builder file. The utility area shows properties for the selected object.

When you turn on the Assistant editor, Xcode 4 will automatically open the correct header file for you.

Generating Code Using Assistant Editor and Integrated Interface Builder

The most important feature that has been added to Xcode 4’s integrated Interface Builder is the capability to generate properties (IBOutlet) or event handling (IBAction) code directly from IB. When the Assistant editor is open, all you have to do is command-click and drag objects to the header file to generate properties, or command-click and drag events from the Utility area to the header to generate IBActions. If your drag destination is valid, Xcode shows an insertion marker and adds the code right in. No connections needed. It’s all done for you.

LLVM Compiler 3.0: A Tryst with the Brain

Xcode 3 and prior versions were not as “intelligent” compared to competing IDE such as Eclipse or Visual Studio. The main reason for this is that Xcode 3 used GCC as the compiler. While GCC is a good compiler, it doesn’t offer much interoperability with the IDE. A compiler normally has a front end that converts source code into an intermediate representation and expands preprocessor macro definitions. It also has a back end that generates code and optimizes it. The GCC compiler is essentially a back-end compiler, which means that when you provide it with source code, it generates compiled binary for it. It was primarily developed for compiling code and not for parsing it. Essentially, this means that Apple has to write its own version of parsers to assist you with debugging. GCC is GPL, so Apple’s version of parsers cannot use the same GCC code without changing the Xcode license to GPL. Because Apple’s parsers and GCC are from different code base, there were always some discrepancies between what the GCC compiler “thinks” and what Xcode “thinks.”

The Clang Front End

To alleviate this problem, Apple is slowly switching to the LLVM compiler. With Xcode 4.2 debuting with iOS 5, the default compiler is LLVM compiler 3.0. Although LLVM is not as “efficient” as GCC in code generation, it’s more modular and extensible. LLVM is also more than twice as fast in terms of compile time (thereby increasing your productivity). A number of front ends have been developed for LLVM, and one of these is Clang, which is heavily funded by Apple. (Clang stands for C language.) Clang supports incremental compilation, which means that the IDE can actually compile the code as you type and show you near-instantaneous compilation errors. You will find this very useful when you start using Xcode 4.

A clear example of this is that Xcode 3 suggests nearly every symbol indexed after you type @synthesize, but Xcode 4 shows suggestions only of the properties in the corresponding header file. Moreover, the modular nature of Clang makes it easy to support code refactoring and features like Edit All in Scope.

I’m a Bug! Fix Me

LLVM’s tighter integration with IDE also helps Xcode 4 to offer suggestions about what the developer must do when the compiler encounters an error. This feature is called Fix-it.

Figure 2-7 shows a suggestion to remove the closing square brackets to match the number of opening brackets.

Figure 2-7 Xcode 4 Fix-it in action

Git Your Versions Here

Another interesting feature addition to Xcode 4 is the integrated Git version control system. Git is a distributed version control system written by Linus Torvalds (yes, the same guy behind the Linux kernel) primarily to maintain the Linux kernel repository. The distributed nature, speed, reliability, cheap branching, and the ability to easily do nonlinear software development encouraged more and more users to adopt Git.

Integrated Git Version Control System