iOS 5: KEY TOOLS AND TECHNOLOGIES

RICHARD WARREN CHAPTER 1 Automatic (ARC)

In the past, has been one of the most challenging parts of iOS development.

ARC helps simplify memory management, by analyzing your code and automatically inserting the necessary retain, release, and autorelease method calls. Memory Management Basics

•Local variables are created on the stack. They are automatically deleted once the current function returns. •To store a value beyond the current function, you must allocate memory on the heap. That value will then remain until we release them. •All Objective- objects are created on the heap. In Objective-C, when we talk about memory management, we are typically talking about managing objects on the heap. •There are two main memory management errors: •Forgetting to release memory on the heap creates a . •Releasing memory too early, then trying to access it again creates a . •In the most simple examples, memory management seems easy. However, in any real-world application, it is often difficult to determine who should be responsible for allocating and releasing the required memory.

2 Retain and Release

We manage the lifecycle of Objective-C objects using their retain count. •All Objects start with a retain count of 1. •Calling retain on an object, increases its retain count by 1.

•Calling release, decreases its retain count.

•Calling autorelease reduces the object’s retain count by 1 at some point in the future (usually at the end of the current run loop). •When the retain count hits 0, the object is deallocated. •If you create an object using a method whose name begins with alloc, new, copy, or mutableCopy, you own the object. You must release it when you are done.

•If you receive an object using any other method, you must retain the object if you wish to keep it past the current method call. •You can get more information on in Apple’s Advanced Memory Management Programming Guide.

3 Problems with Manual Memory Management

Manual retain and release (MRR) has served Objective-C well for over 3 decades. It’s a solid system and has been used to create hundreds of thousands of high-quality applications. However, MRR still has a few problems.

•Inserting the correct retain, release and autorelease calls is tedious. •The developer must constantly think about where their objects are coming from. Do they own the objects, or will the objects be autoreleased. •The manual memory management must be correct 100% of the time. Even one mistake can cause a memory leak or dangling pointer. •The developer’s energy and attention could be better spent solving interesting problems, not managing memory. •You can also create retain cycles. If two objects retain each other, they will never be released. •Apple has provided a number of tools, like Instruments, to track memory usage and help eliminate memory bugs. •Still, memory-related bugs are the #1 reason why iOS applications crash. 4 Garbage Collection

To address these problems, Apple introduced garbage collection with Mac OS X 10.5, Leopard. •A garbage collector runs on a low-priority background thread. •It monitors all references to Objective-C objects. •When it determines that an object is no longer being used by the application, it deallocates the object. •This greatly simplified developing applications for the Mac, but it has some problems. •Developers have very little control over when and how the garbage collector runs. •If objects are rapidly created and released, memory usage can spike, causing the application to use too much memory, before the garbage collector can catch up. •Alternatively, the garbage collector may unexpectedly run, slowing down the application at a critical moment. •Most importantly, garbage collection is not available for iOS.

5 Introducing ARC

ARC is a compiler feature that provides automated memory management for Objective-C objects. Conceptually, ARC follows the retain and release memory management conventions. As your project compiles, ARC analyzes the code and automatically adds the necessary retain, release, and autorelease method calls. •ARC largely frees developers from worrying about memory management. •Memory management is handled at compile-time. •There are no unexpected slowdowns during the application’s execution. •The developer maintains control over when and how objects are deleted from memory. •Apple has also optimized memory management under ARC. Basic retain and release calls are 2.5 times faster than MRR, and auto release pools can be up to 6x faster. •There are some additional rules that we must follow--however the compiler enforces these. •Unfortunately, ARC does not protect us from creating retain cycles.

6 Zeroing Weak References

The objects in our application can be seen as a directional graph, starting with the UIApplication instance, and moving down through our custom data. Whenever we create a reference to an object (e.g. an object @property in one of our classes), we need to consider whether it refers to a new object, or if it refers back to an object further up in our graph.

•If we are referring to a new object, we should use a strong reference. This tells ARC to retain the object for us.

•If we are referring back up the graph, we need to use a . This tells ARC to use a zeroing weak reference. •ARC will not retain the object. It must be retained somewhere else (using a strong reference), or it will not remain in memory. •If the object is ever deallocated, the zeroing weak reference will automatically be to nil. This eliminates any chance of having dangling pointers.

•Objects should always use weak references to their delegates.

7 ARC Rules of the Road

•Don’t use objects in C structs. •Don’t create a property with a name that begins with “new.” •Don’t call dealloc, retain, release, retainCount, or autorelease.

•Don’t override the retain, release, retainCount, or autorelease methods.

•You can override dealloc, but it’s often not necessary.

•When implementing dealloc, don’t call [super dealloc].

•Don’t use NSAutoreleasePool objects. Use the new @autoreleasepool{} blocks instead.

•Use __bridge __bridge_retain or __bridge_transfer when casting between objects and void*.

•Don’t use NSAllocateObject or NSDeallocateObject.

•Don’t use memory zones or NSZone.

8 Demo

9 CHAPTER 2 Storyboards

Interface Builder (now part of ) has long allowed developers to graphically design their application’s user interface. Even letting developers draw connections between control events and methods in their code.

Now, Storyboards takes this one step further. We can not only create an individual scene--we can graphically lay out the relationships and segues between scenes. Interface Builder and Nibs

•Unlike many visual tools, Interface Builder does not generate code to create your user interface. Instead, it constructs the interface from live objects, then archives them. •Traditionally, the interface archive is a binary .nib file. When you load a nib, you are loading all the objects that make up the user interface. •Recent versions of Xcode allow saving the interface as XML to better support source control and diff tools. •Modern projects save the files as .xib files, then compile the .xib to a .nib file in the final product. •The terms nib and xib are generally used interchangeably. •Each nib file has a file’s owner. You can draw connections from the owner to objects created by the nib.

•IBOutlet allows you to connect instance variables to objects in the nib.

•IBAction allows you to connect methods to UIController events in the nib.

11 Nib Demo Storyboards

Storyboards extends Interface Builder’s power. While nibs let us define a screenful of information, Storyboards let us graphically lay out the relationships and transitions between screens. •A storyboard has the following features: •One or more scenes. Each scene represents a significant chunk of information on the screen. •Relationships between containers (navigation view controller, tab view controller, etc.) and their content. •Segues between scenes. •At compile time, the storyboard is converted into nib files. •Each scene roughly translates to its own nib file. •There isn’t a strict 1:1 relationship between scenes and nibs.

13 Using Storyboards

•Storyboards are only supported by iOS 5 and later. If you want to support earlier versions, you cannot use Storyboards. •You can freely mix Storyboards and nibs inside a single project. However, you must load each new Storyboard or nib in code. A storyboard cannot load a nib or another Storyboard. •One nib can refer to another nib; however, this is not supported in Storyboards. This means we can do some things in nibs that we cannot yet replicate with Storyboards. •You cannot draw connections between the objects of one scene and another. All connections must be drawn within a single scene, with only segues and relationships leading out to other scenes. •Storyboards are most useful when first creating a project: •You can quickly sketch out the framework and workflow for the entire application. •This can save a lot of time when initially setting up the application.

14 Passing Data Across Segues

•Before the application segues from one scene to the next, the originating scene’s view controller’s prepareForSegue:sender: method is called.

•We should override prepareForSegue:sender: and pass the data we need to the destination’s view controller. •Note: the destination view may not exist yet. We should store the data in the view controller, then pass it to the view in its viewWillAppear: method. •To get data back from the destination, we should make the sending view controller a delegate of the destination. •We must define the delegate protocol ourselves. •We assign the sender as the destination’s delegate in prepareForSegue:sender:.

15 Storyboard Demo CHAPTER 3 iCloud

While Apple has attached the term iCloud to a dizzying range of products and services, as developers, we are only concerned with iCloud Storage. iCloud Storage is a cloud-based technology, that lets our application sync its data across all of our user’s devices (iOS, Mac and PC). iCloud is NOT:

Often, the largest problems with iCloud come from developers trying to get it to do things that are really outside its scope. iCloud cannot be used for any of the following: •Remote Storage. Our apps still run off local copies of their data. •Communication between users. While we can, in a limited way, create URLs to let others access data inside iCloud, we cannot use iCloud to create the next Twitter. •General communication between apps. iCloud can let us sync between a relatively narrow suite of applications (e.g. the lite and full versions of an app); however, we cannot use it as a general channel to sync between apps from different developers.

18 So, what IS it?

•A technology for syncing data and documents. •One user. •One app. •Or, a tightly integrated suite of apps from a single development team.

19 iCloud Storage APIs iCloud Storage has two APIs: •iCloud Key-Value Storage This is a simple, stripped down API. In many ways, it resembles the NSUserDefaults API. •Most often used to sync user defaults. •No Conflict Resolution. Last entry wins. •After a few changes, updates are throttled. •Limited to 64 KB. •iCloud Document Storage A feature-rich API used to sync user-generated data and application data. Unfortunately, the API is also much more complex, and difficult to use.

•UIDocument and UIManagedDocument make using document storage easier. •Easier ≠ Easy!

20

Steps for Implementing iCloud Document Storage

•Setup the application’s entitlements •Initialize the iCloud container (verify that iCloud is enabled) •Search for existing documents in iCloud using NSMetadataQuery •Create new documents and move them into iCloud •Coordinate all read/write operations using an NSFilePresenter and NSCoordinator •Identify and resolve document conflicts •Listen to and handle other document state changes (e.g. update and saving errors).

24 UIDocument

•Automatically saves data on a background thread. •Atomically, safely saves the document. •Coordinates reading and writing with the background thread. •Supports discovery of conflicts. •Provides undo/redo support. •UIDocument is an abstract class, you must subclass it to use it.

•“Just” override two methods: contentsForType:error: and loadFromContents:ofType:error: •Notify the document of any changes. •Handle conflicts as they arise. •Listen for other document state change notifications. •Still requires code to set up iCloud, find or open files, etc.

25 UIManagedDocument

•A concrete subclass of UIDocument, specifically designed to work with Core Data. •Automatically sets up the Core Data stack. •Automatically provides per-record conflict resolutions. •Much easier to use than UIDocument--but requires Core Data.

26 CHAPTER 4 UIAppearance

With iOS 5, Apple has provided an API for customizing the appearance of many common controls.

The new Appearance API allows us to change the appearance of an individual control, change the appearance of all instances embedded in a specified container, or even globally changing the appearance of all instances across the entire application. Supported Controls

•UIActivityIndicatorView •UIBarButtonItem •UIBarItem •UINavigationBar •UIProgressView •UISearchBar •UISegmentedControl •UISlider •UISwitch •UITabBar •UITabBarItem •UIToolBar

28 Demo CHAPTER 5 Controller Containers iOS has always had two types of view controller. The typical view controller helps manage the contents of one or more views. As developers, we created these view controllers for our apps. However, some controllers, like the UINavigationController or UITabBarController focused on managing other view controllers. These container controllers were exclusively developed by Apple. With the release of iOS 5, Apple has formalized the idea of a view controller hierarchy. More importantly, they now let us create our own custom view controller containers. UIViewController Containers

•A UIViewController Container manages one or more child UIViewControllers. •The container must add each child’s root view to its own view hierarchy. •It should also set the size and position of the child’s root view. •You may use the following methods and properties to manage child view controllers: •addChildViewController: •removeFromParentViewController •transitionFromViewController:toViewController:duration: options:animations:completion: •childViewControllers •These methods should only be called inside a custom controller container. Do not call these methods on any other view controllers.

31 View Controller Hierarchy iOS expects both the views and the view controllers to be in well-formed hierarchy. The system will pass a number of methods along these hierarchies. If your view controllers are not set up properly, they may not receive some of these messages. While this may not be immediately obvious, it can lead to unexpected or unpredictable behaviors.

Basic Rule: if you create a UIViewController subclass for a view, then you must add both the view and its controller to their corresponding hierarchies.

Remember: you don’t need to create a UIViewController subclass for each custom view. A single view controller can manage a large number of views.

32 Demo CHAPTER 6 Twitter Integration

iOS 5’s Twitter integration both provides a convenient method for sending tweets from within your application using the TWTweetComposeViewController.

It also provides access to the full Twitter API using TWRequest and the Account Framework. Demo CHAPTER 7 Core Image

The Core Image framework has provided a rich range of image manipulation filters and tools. Finally, with iOS 5, the full power of Core Image has been brought to our mobile devices.

This includes the ability to detect faces using the CIDetector and CIFaceFeature classes. Demo CHAPTER 8 Core Data Additions

Core Data is a large, complex topic. This lesson will only focus on iOS 5’s additions to Core Data.

For a more complete overview of Core Data, please see Creating iOS 5 Apps: Develop and Design, Chapter 7. iOS 5 Core Data Additions

•UIManagedDocument sets up a complete Core Data stack. •Persistent stores use encryption by default. •Offers 3 different multi-threading options for the NSManagedObjectContext: •Thread Confinement (old system) •Main Dispatch Queue •Private Dispatch Queue •Added performBlock: and performBlockAndWait: methods to support multi- threading access. •Allows nested managed object contexts. •Added support for ordered relationships and externally stored attributes. •We can implement support for non-atomic persistent stores using the new NSIncrementalStore and NSIncrementalStoreNode classes.

39 CHAPTER 9 Newsstand Apps

iOS 5 also provides support for Newsstand applications. Unlike normal apps, these applications only appear inside the Newsstand. Instead of displaying an application icon, the Newsstand will display the cover of the latest issue.

Developers typically use newsstand applications to build interactive magazines and newspapers. Content Servers

Newsstand applications require coordination between the application and your content servers. The content servers must send the following information: •Push notifications whenever updated content is available. •The content for the latest issue. •The cover art for the latest issue. When your application receives the push notification, it will launch itself in the background and begin downloading the latest issue. The download is managed by the system, which notifies your app once the download is complete. The app will be launched for updates at most once in a 24-hour period.

41 Newsstand Kit Framework

The Newsstand kit framework is primarily geared towards helping you download and manage issues and assets. It does not define how each issue’s assets are used by your application. That is up to the individual application. The framework consists of three classes: •NKLibrary Represents the collection of issues within the application. •NKIssue Represents a single issue of the publication. You can access the issue’s name, data and status. You also use this class to request assets. •NKAssetDownload Represents an asset that is being downloaded or that has been downloaded. You can use this class to download individual assets (images, html, etc.). Or, you can bundle all of the issues assets into a single zip file and download all the content at once (recommended).

42