Creating New Files in Xcode 4.5

This is an update to a number of older posts which involved creating new files in Xcode by selecting a specific subclassing option. This has changed in recent versions of Xcode; this is the way to do it as of Xcode 4.5 (the latest at the time of writing).

  1. Go to File > New > File… (or press Command-N)
  2. On the left of the sheet that appears, select Cocoa Touch under iOS. On the right, select Objective-C class. Click Next
    Creating a New File—Select File Type

    Creating a New File—Select File Type

  3. For “Class”, specify the name of your class. “Subclass of” lets you select a superclass; this selection changes the options you see below (for example, “With XIB for user interface” appears only when you’re subclassing a view controller). You can also type in a name and make a subclass of one of your custom classes.
    Creating a New File—Specify a Superclass

    Creating a New File—Specify a Superclass

  4. Click Next, pick a save location, and click Create. You should see your files appear in the File Navigator.

The Jungle, Part 9: Core Data

Core Data

This post will explore the depths of the Core Data API. Core Data is a technology that manages a complex SQL database, and wraps the C function calls into an object-oriented framework that is much easier to use. This database structure allows you to store complex data objects, and a lot of it—the whole system is incredibly efficient, potentially handling millions of items with ease.

We’ll create a project that creates, stores and displays a list of random colors. We will look at building the object model and the equivalent classes that result, working with objects in the database, and displaying the results in a table view. Core Data is set up to work seamlessly with the UITableViewDataSource; the data structure is almost completely in place already.

Xcode empty project

Create an empty project in Xcode

We’ll begin by creating an Empty Application. On the next screen, make sure “Use Core Data” is checked.

Use Core Data checkbox

Use Core Data

The “Use Core Data” checkbox mainly does three things—it links in the Core Data framework, creates a data model file, and creates and initializes the Core Data stack. The stack describes the architecture of Core Data, so that’s a great a starting point.

Core Data Objects

Core Data Objects

The Core Data stack

Every Core Data project starts with the data model. In our app, it’s called “ColorsDemo.xcdatamodeld”. This file, which comes with its own editor mode, lets you define the data structure of your project, which is comprised of the classes as well as their associated properties, along with the relationships between the classes.

The persistent object store represents the stored data file on disk; you normally don’t interact with the object store.

The persistent store coordinator is your more direct access to the data store; it is the connection to the database. Big Core Data projects can have their data model spread over several data model files; each one corresponds to an object store. The persistent store coordinator coordinates the interactions with each store file on disk; there is only one coordinator per stack.

The managed object model represents the objects in the data store during the execution of the program. It contains information about the objects (“entities”) you defined in the data store; it gets an aggregate of all the entities across all the store files from the persistent store coordinator.

The managed object context is where a lot of the interaction with Core Data occurs. This is where objects are created, modified, and then committed to disk. Apple calls this a “scratch pad for managed objects”.

The Data Model

Open the data model file. The editor contains a list (currently empty) of Entities (objects), Fetch Requests (you send fetch requests to find stuff in the database), and Configurations (used when you want to deal with subsets of multiple data stores. This is beyond the scope of this post). Click the + (“Add Entity”) button at the bottom to add an entity. An item should appear in the list, under Entities, with its name highlighted. Change the name to “Color”.

Creating an entity in the editor

Creating an entity in the editor

In the middle pane of the editor, you’ll see an area labelled “Attributes”. Here is where you define the entity’s attributes, analogous to properties in regular objects. Click the plus button at the bottom left of the Attributes block to create a new attribute. It should be called red, and it should be of type Float (select from the popup menu that appears when you click on the default value, Undefined.

In the Attributes inspector, uncheck the Optional checkbox. “Optional” indicates that the attribute doesn’t have to have a value, but in our case it doesn’t make sense for our color not to have a red value. Therefore, it shouldn’t be Optional. You’ll also see “Indexed”, which means that the value should be added to the database index, which makes searching faster. However, we won’t be searching by a specific color value, so we can leave it out of the index. Adding values to the index will allow searches on those values to be faster, but a large index will slow down searches in general. Therefore, add only the values you actually intend to search. You’ll also see “Transient”, which signifies that the attribute is not actually stored to disk, but calculated in code. Core Data doesn’t make sure that the value actually is calculated; it is your responsibility to make sure that a transient attribute has a valid value when you try to access it.

You can also specify minimum, maximum, and default values for the attribute. For our red attribute, we set a minimum value of 0 and a max of 1. This range of values represents how UIColor accepts color values, and simplifies things. Core Data will enforce the limits and raise an exception if you try to store a value outside of this range. The default value is simply the value that the attribute gets created with. It’s not necessary to supply a default value, but it is a good idea to do so, especially for attributes that are not optional.

Attributes inspector

Attributes inspector

Create two more attributes with the same type and properties; call them green and blue. Also create an attribute of type String; call it name. Make sure it’s not Optional, that it is Indexed, and give it a default value of “Unnamed Color”. You can check a string by a minimum or maximum length, but we’re not going to impose length restrictions on our color names; you can also supply a regular expression to validate the input. Regular expressions (regexs) are beyond the scope of this post.

Now we’ve fully defined our Color entity in the editor. We can have Xcode generate the class template for us. Make sure the Color entity is selected, then go to Editor > Create NSManagedObject Subclass…:

Create NSManagedObject Subclass

Create NSManagedObject Subclass

Make sure “Use scalar properties for primitive data types” is checked. This setting creates ints and floats for properties rather than wrapping them up in NSNumber. This makes things faster, and because we’re simply using our values to create instances of UIColor, there’s no reason not to. Accept the default save location and click “Create”. You’ll see “Color.h” and “Color.m” appear in the File Inspector, and Xcode has generated property declarations for you already.

Xcode generates property declarations

Xcode generates property declarations

Toggle over to Color.m, and you’ll see something new: @dynamic. This is similar to @synthesize, except that the getter and setter methods aren’t generated by the compiler. In fact, @dynamic tells the compiler to assume that the methods are there and ignore the warnings that it would otherwise raise about the missing methods; Core Data inserts the appropriate methods in at runtime. However, you can still write your own getters and setters; Core Data will never override your code.

Add a readonly property to Color of type UIColor and call it derivedColor. This property is read-only because it is actually generated from the individual color components each time it is accessed. The getter looks like this:

- (UIColor *)derivedColor {
	return [UIColor alpha:1.0];

It would be more efficient to save a copy of the UIColor and only create a new one if the component colors were changed, but that’s a level of complexity that would distract from the main purpose of this post.

Building the UI

Now that we’ve defined the data structure, we can get around to building our UI. To do that, we’ll have to create a view controller and wire it up. In fact, for this project we’re going to create a navigation controller, providing room for a detail view controller which lets us explore more of what Core Data has to offer. Begin by pressing Command-N to create a new Objective-C class. Call it ColorsListViewController and make it a subclass of UITableViewController. Make sure you create the corresponding XIB as well.

Head over to AppDelegate.m. Import ColorsListViewController.h, and then in application:didFinishLaunchingWithOptions:, after the “Override point for customization” comment, add the following code to initialize our view controller, create the nav stack, and add it to the main window:

	ColorsListViewController *mainVC = [[ColorsListViewController alloc] init];
	UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:mainVC];
	self.window.rootViewController = navVC;

Next, we’re going to create a button that will create a new random color and add it to the table. Add the following code to viewDidLoad:

	UIBarButtonItem *plusButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewColor:)];
	self.navigationItem.rightBarButtonItem = plusButton;
Contacts Plus Button

Contacts Plus Button

We’re creating a standard plus button (like the one you see in the Contacts app), binding it to the addNewColor: method (which we’ll be defining in just a moment), and adding it to the right position in the nav bar.

Next, add the method declaration for addNewColor: to the header file and the following implementation:

- (IBAction)addNewColor:(id)sender {
	AppDelegate *ad = (AppDelegate *)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *moc = ad.managedObjectContext;
	Color *newColor = (Color *)[NSEntityDescription insertNewObjectForEntityForName:@"Color" inManagedObjectContext:moc]; = [self randomColorComponentValue]; = [self randomColorComponentValue]; = [self randomColorComponentValue];
	NSError *error;
	if (![moc save:&error]) {
		// Something's gone seriously wrong
		NSLog(@"Error saving new color: %@", [error localizedDescription]);
	[self.colorsArray addObject:newColor];
	[self.tableView reloadData];

Make sure to import AppDelegate.h and Color.h. You’ll also need to declare colorsArray as a property of type NSMutableArray. We’re also using a helper method to generate a random number between 0 and 1. In this method, arc4random() returns a value between 0 and 2^32-1, so we divide the return value by 2^32-1 (equivalent to 100000000 in hexadecimal).

- (double)randomColorComponentValue {
	return ((double)arc4random() / 0x100000000);

Let’s take a look at what addNewColor: is doing. We get a reference to our app delegate because that’s where our managed object context is (Xcode’s Core Data template created the object for us. If you’re interested in where the object comes from, take a look at AppDelegate.m). We then get the managed object context itself. Next, we create a new instance of Color by adding a new object to the database. This is an important paradigm to understand. The insertNewObjectForEntityForName:inManagedObjectContext: method takes the name of the entity (our data model class) as its first argument, and the managed object context as its second. The method returns an object of type id; we cast it to an instance of Color. We then set the color components to a random value, and then save the color to our database using the managed object context. If save: fails, the method returns NO and our error will be set to something appropriate. It is a serious issue if the save fails; depending on the situation, the app should try again, ask the user to try again, or simply choose to crash if the data is unrecoverable and the app can’t continue without it (an extreme case). In this case, we just log the error. The rest of the method is simple: we also add the color object to the array that backs the table view, and then reload the table view.

Next, we’re going to populate our colorsArray in viewDidLoad so it contains data from whatever is already stored on disk. After alloc/initing the array, add the following code:

NSManagedObjectContext *moc = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Color" inManagedObjectContext:moc];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    [request setSortDescriptors:sortDescriptors];
    // Fetch the records and handle an error
    NSError *error;
    self.colorsArray = [[moc executeFetchRequest:request error:&error] mutableCopy];
    if (!self.colorsArray) {
        // This is a serious error
		// Handle accordingly
		NSLog(@"Failed to load colors from disk");

We begin by grabbing our managed object context again. Then we create an entity description, again passing in the name of our entity as a string. We then create a fetch request (a request to get stuff from the database) and set our entity description as the entity to fetch from the database. We then create a sort descriptor, which takes a key (the name of a property, the same type of key that key-value coding uses) and a sorting direction. Core Data handles the sorting logic for a variety of data types, including strings, numbers, and dates, but there are ways to custom sorting in a fetch request as well. We add our sort descriptor to an array (because our request wants an array), and set that on our fetch request. Then we tell our managed object context to perform the fetch request, and we create a mutable copy of the array that is returned, setting it to our colorsArray. If something goes wrong, we’ll have to handle the error accordingly.

Now it’s elementary to set up our table view data source methods:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.colorsArray count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *cellID = @"CellID";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
	if (!cell) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	Color *currentColor = [self.colorsArray objectAtIndex:indexPath.row];
	cell.textLabel.text =;
	cell.detailTextLabel.text = [NSString stringWithFormat:@"Red: %.3f Green: %.3f Blue: %.3f",,,];
	return cell;

There’s nothing new here; we’re just pulling values from our colorsArray and setting the text labels in our table view cell.

Build and run the app. You’ll be presented with a blank table view. Press the “+” button a couple of times, and new entries will appear in the table. Now, you can quit the app, and when you relaunch the entries will be right as you left them. That’s the persistent nature of Core Data at work.

A few entries saved with Core Data

A few entries saved with Core Data

Building the Detail View

We’ve played around with the basics of Core Data, but we can do more. We’re going to build a detail view that allows us to edit color names, see what our color looks like, and delete colors. Changes that we make will be written back to the database. Let’s get started by creating a subclass of UIViewController, call it DetailedColorViewController, and make sure to create the XIB as well.

Detailed view controller XIB layout

Detailed view controller XIB layout

The UI should look something like this. The first element is actually a borderless text field, with the text centered and set to size 24. In the middle is a generic UIView; we can change the background color to reflect the actual color that we’re representing. Finally, we have a button that will delete the color.

Declare these two methods in the header. Wire up the first one to the text field’s Did End on Exit event, and the second to the button’s Touch Up Inside event.

- (IBAction)didChangeColorName:(id)sender;
- (IBAction)deleteColor:(id)sender;

Also declare a property (strong, nonatomic) of type Color, called color, and import Color.h. Synthesize the property in the implementation file. The text field should also be hooked up to a corresponding property called nameField, and the basic view should be hooked up to a corresponding property called colorView. Make sure both are strong and nonatomic, and that both are IBOutlets.

A few lines of code are needed in viewDidLoad to set up the view.

	self.title = @"Inspect Color";
	self.nameField.text =;
	self.colorView.backgroundColor = self.color.derivedColor;

Next, we’re going to implement the delete method. Again, the managed object context is our point of interaction, and the code is pretty simple. Ideally, you’d like to prompt the user with an action sheet to confirm the delete action, but for simplicity’s sake we’re simply going to go ahead with the delete here.

- (IBAction)deleteColor:(id)sender {
	NSManagedObjectContext *moc = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	[moc deleteObject:self.color];
	[moc save:nil];
	[self.navigationController popViewControllerAnimated:YES];

We first get the managed object context (make sure to import AppDelegate.h). Then we simply call deleteObject:, passing the Color object we’re referring to here. We save the changes to disk; for simplicity’s sake we won’t concern ourselves with any errors. Then, we pop to the list view because our detail view is now referring to a Color that no longer exists.

Updating a managed object is as simple as updating the properties you want, and then saving the changes through the managed object context. NSManagedObject associates each object with a managed object context, which makes Core Data interactions much simpler.

- (IBAction)didChangeColorName:(id)sender { = self.nameField.text;
	[sender resignFirstResponder];
	NSManagedObjectContext *moc = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
	[moc save:nil];

A detail worth pointing out: The color’s name is set to the value stored in our nameField, because that’s the purpose of the name field. However, resignFirstResponder (which dismisses the keyboard) is called on the sender. This allows our method to be more modular; we could connect the method to other (or even multiple) UI elements and it would still behave properly.

Now all we have to do is support the detailed view controller in our list view controller. Head back over to ColorsListViewController.m. Import DetailedColorViewController.h and implement the relevant delegate method:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	DetailedColorViewController *dcvc = [[DetailedColorViewController alloc] init];
	dcvc.color = [self.colorsArray objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:dcvc animated:YES];

In viewWillAppear, we’ll refresh our table view because changes could have been made in the detailed view controller.

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[self.tableView reloadData];

Build and run the app. Try changing a color name, hitting Return on the keyboard and going back to the list view. The entry will update to reflect your new name. Try deleting an entry and going back to the list view. In fact, you’ll notice that we end up with an entry without a name, where all the color components are 0. This is because our colorsArray wasn’t updated with the change. It still holds three items, although one of them is now effectively nil. Quitting and restarting the app will fix the issue, but we can fix it in code as well. Simply move the code in viewDidLoad fetching from disk (from getting the managed object context to the error handling if colorsArray is nil) into a separate method called fetchColorsFromDisk, and call that method at the end of viewDidLoad, and right before reloading the table view in viewWillAppear:

Modified Core Data entries

Modified Core Data entries

As you can see, Core Data provides an easy way to save data to disk. There is some initial architecture to sort through (although the Core Data template helps a bunch—see AppDelegate.m for all the rest of the code), but Core Data makes it incredibly easy to propagate changes to disk. Most of our code was UI code, presenting the information on disk.

Core Data’s real power comes from its speed and searching ability. You can handle databases of thousands of objects without perceived lag, and you have very powerful search tools at your disposal. Core Data also provides a way for you to migrate to future data model versions if you ever decide to change the way the data is represented. There’s a lot more to Core Data, but hopefully this was a helpful introduction! There will be more posts on Core Data in the future.

Adding Frameworks to an Xcode Project

A lot of Xcode projects require you to add additional frameworks to link against. Here’s how:

  1. Select the main project listing in the left column.
    Select Project

    Select Project

  2. Select Build Phases from the tabs near the top.
    Build Phases Tab

    Build Phases Tab

  3. Click the ‘+’ button in the “Link Binary With Libraries” section (you may have to twist it open.
    Select Frameworks

    Select Frameworks

  4. Choose the framework(s) you want to add, and click the “Add” button.
    Add Frameworks

    Add Frameworks

The Jungle, Part 6: Navigation Controllers and Stacks

Navigation controllers are a cornerstone of iOS—they allow you to present a lot more information than you could fit on one screen, in a hierarchical format that is intuitive to the user. What does that mean? Think of it as a deck of cards (to use an oft-quoted metaphor). You have a stack of views with a “vertical” order. You can only see the top view, but there can be views underneath, and you can put views on top. And nav controllers are everywhere, so users are already familiar with it.

A UINavigationController handles the nav stack, as well as the corresponding animations. All you have to do is push and pop views controllers, if necessary. You will usually have to push view controllers on the stack, but by default, the back arrow in the upper-left will pop the controller automatically. You do have the ability to pop any number of existing view controllers programmatically if you need to—for example, in an app with a tab bar, tapping on a tab will take you to the root controller (first controller), which means that if you’re already in that tab, it’ll programmatically pop to the root controller.

Tab bar controllers and nav controllers are often seen together. In these situations you have some choices as to the design of the app. If each tab is displaying different content, you may want each tab to contain its own nav controller as the tab’s assigned view controller. Alternatively, if your different tabs just show a different sorting order or a different view on the same data, you might want to have the tab bar exist independently of the nav controller, and simply refresh the nav controller’s view when a different tab is selected. It is a bad idea to have each nav controller own its tab bar; you should not change your tab bar across different views of your app.

We’ll add navigation to our demo app, so open up the app that we’ve been working on not too long ago. Create a new UIViewController and call it CustomDrawingViewController (yes, next post we’ll look at doing some custom drawing using Quartz/Core Graphics—same thing). We’ll add a property that will allow you to set the title of the view before you push it on. Declare and synthesize a property of type NSString called viewTitle. Assign that property as the title in viewDidLoad:

if (!self.viewTitle)
		self.title = @"Custom Drawing";
		self.title = self.viewTitle;

If the property did not get set, it’ll use the generic “Custom Drawing” title; otherwise it uses whatever was set. Now go to GraphicsTableViewController.m, where we’ll push the view controller. We do that in tableView:didSelectRowAtIndexPath:. Replace the deselect method with the following:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomDrawingViewController *drawingVC = [[CustomDrawingViewController alloc] init];
	drawingVC.viewTitle = [[tableView cellForRowAtIndexPath:indexPath] textLabel].text;
	[self.navigationController pushViewController:drawingVC animated:YES];

Import CustomDrawingViewController.h. In this code, we create an instance of our new view controller. We set the title to be the text of the table view cell that was just tapped. Finally, we push on the new view controller. Note the call to self.navigationController. Nav controllers are so common in iOS that UIViewController contains a property to a parent navigation controller. If the view controller is not a child of a nav controller, then the property will be nil. Also note the animated parameter in the last method. You always want to animate the change if it’s going to be visible. Put another way, the only time you don’t want to animate is if you’re loading the first view of a stack, because the animation won’t be seen anyway.

Build and run, and select the Graphics Demo tab. Tap on any cell, and you’ll see an animation to a blank screen.

Nav Controller

Pushing on a new view

There will also be a back arrow in the upper left. Tap on that to go back.

Download the current version here.

Extension: Rotation

In this post we’ll talk about how to handle rotating a UI. We’ll start by using existing constructs to allow our views to support rotation, and then discuss complications and their solutions. Start with a new Single View Application and call it AutoRotate. As usual, I’ll be using ARC. Open the main view controller’s implementation.

Enabling Rotation in Code

First, we have to tell the system that the view controller supports rotation and that it should rotate to a specific orientation. We do this by implementing an existing method on UIViewController:

#pragma mark - Rotation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
	return (toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);

The method might already exist in the file, provided by the template. In that case, simply change the method contents.

In this method, we’re returning a boolean value that tells the system whether to rotate to a specific orientation. We return YES for all supported orientations. Note though that we are not supporting UIInterfaceOrientationPortraitUpsideDown. Apple’s guidelines state that the upside-down orientation should not be supported unless necessary, because might end up being confused about which way is up, an important feature of phones. Of course, this distinction isn’t made on the iPad, and Apple strongly recommends to support all four orientations on iPad. But for now, we’ll support all except upside-down.

Now we’ll build the interface and implement the actual rotation logic—open the XIB. Design an interface like this one. It doesn’t matter exactly what you use, but keep it simple with some of the basic UI elements. The bar at the bottom is a UIToolbar. I put three UIBarButtonItems on it and two Flexible Spacers in between.

Initial View

Initial View

We don’t need to hook up any of the elements, because we’re just concerned with rotating the view. Build and run the app.

Initial View in Simulator

Initial View in Simulator

You can rotate the iPhone Simulator by 90 degrees at a time. Go to the Hardware menu, and then select Rotate Left or Rotate Right. You can also use Command-LeftArrow or Command-RightArrow. The rotation will be accompanied by a corresponding animation, and you’re left with a view that look like this:

Mangled Rotation

Mangled Rotation

While the background rotated (along with the bottom toolbar, which is handled by the system, the rest of the view didn’t change. We can fix that with a few different ways.

Struts and Springs

Struts and springs are a simple IB construct that gives you a few options to stretch and position views. Select the “1” button and go to the Size Inspector (the one with the Ruler icon). You’ll see a section called Autosizing. If you mouse over the Example area to the right, it’ll animate to show you the changes.

Autosizing UI

Autosizing UI

The autosizing area is where you make the changes. You’ll see a square with I-beams (struts) on the outside and double arrows (springs) on the inside. The I-beams on the outside acts as “anchors” to the sides of the containing view. The arrows on the inside tell the subview to expand with the containing view. Behavioral conditions:

  • If all the I-beams are enabled, the subview will stay the same size and anchored near (0,0) in the containing view. On the iPhone, that would be the top-left corner.
  • If no I-beams or double arrows are enabled, the subview will stay in the same size in the center of the containing view.
  • If all the double arrows are enabled but no I-beams, the subview will expand proportionally to the containing view.
  • If all the double arrows and I-beams are enabled, the view will expand with the subview, keeping the same distance around all the edges.

You can see all of this happening in the Example.

We can use these struts and springs to position some of the UI. All the buttons and the label should have both springs enabled. The progress view and slider should have the horizontal spring enabled. Button 1 should have the top and left struts enabled; button 2 should have top and right. Button 3 should have just left; button 4 should have just right. The label should have no struts enabled.

The progress view should have just the left strut; the slider just the right strut. The textview at the bottom should have both springs, the bottom, and left and right struts enabled.

Build and run again, and we see something like this:

Struts & Springs UI

Struts & Springs UI

It’s almost perfect. Springs and struts give you some basic flexibility—it moved our buttons and label nicely—but for more complex situations, like the lower part of our view, we need something more robust.

Swapping Views

Swapping views as necessary gives you the flexibility to structure your views any way you want using the convenience of Interface Builder. Begin by adding two outlets to the view controller’s header:

@property (strong, nonatomic) IBOutlet UIView *portraitView;
@property (strong, nonatomic) IBOutlet UIView *landscapeView;

Synthesize the properties and go over to the XIB. Drag out a new view and go to the Attributes Inspector. Under Orientation in Simulated Metrics, select “Landscape”. Build a view similar to this:

Manual Landscape View

Manual Landscape View

Connect the new view as landscapeView, and the old view as portraitView. Go to the implementation file, where we will handle the swap. Add the following code to the bottom of the file, before the @end:

#define degreesToRadians(x) (M_PI * (x) / 180.0)
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
	if (toInterfaceOrientation == UIDeviceOrientationPortrait) {
		self.view = self.portraitView;
		self.view.transform = CGAffineTransformIdentity;
		self.view.transform = CGAffineTransformMakeRotation(degreesToRadians(0)); 
		self.view.bounds = CGRectMake(0.0, 0.0, 320.0, 460.0);
	else if (toInterfaceOrientation == UIDeviceOrientationLandscapeRight) {
		self.view = self.landscapeView;
		self.view.transform = CGAffineTransformIdentity; 
		self.view.transform = CGAffineTransformMakeRotation(degreesToRadians(-90)); 
		self.view.bounds = CGRectMake(0.0, 0.0, 480.0, 300.0);
	else if (toInterfaceOrientation == UIDeviceOrientationLandscapeLeft) {
		self.view = self.landscapeView;
		self.view.transform = CGAffineTransformIdentity; 
		self.view.transform = CGAffineTransformMakeRotation(degreesToRadians(90)); 
		self.view.bounds = CGRectMake(0.0, 0.0, 480.0, 300.0);

We start with a pre-processor macro that converts degrees to radians. iOS uses radians in its graphics work, but it’s easier for us people to think in degrees. Note that in this case, we will have to do some custom graphics work, because we will have to transform the view to match the rotation.

Inside the delegate method, we check for the corresponding orientation and swap the view in the first line of each condition. Then we reset the view’s transformation. We’ll cover transformations in a future post. We use a provided function to make a rotation transformation and apply it to the view. We also change the size of the view to fit the screen. All of these changes happen in the will method, so they are complete before the actual rotation happen, and the correct view will be displayed in time. Note that animating all aspects of the transition would require additional code, which is beyond the scope of this post.

Rotating Tips

On the iPhone, not all apps support all orientations, or even rotation at all. On iPad, apps should support as many orientations as possible—at least both variants one orientation; preferably all four orientations.

Note that landscape and portrait views don’t necessarily have to present the same information, or even the same appearance. The Music app on the iPhone displays a UIKit-based tab bar and table interface in portrait view, but a custom coverflow interface in landscape.

If you’re doing some custom views/drawing, make sure the view animates when you rotate, especially if you’re displaying content such a grid of icons or text. Otherwise, it is a very disorientating experience for the user and might discourage use of your app.

Finally, make sure there is some meaningful change when the user rotates. If you’re just stretching the UI, consider whether it makes sense to rotate, or if rotation is worth the effort. If you have text input, the larger keyboard might be worth it—but you also loose a large portion of the rest of the content. Otherwise, rotating might not be necessary.

Download AutoRotate here.

Extension: Advanced Tables

In this post we’re going to take a step away from our existing project and look at other things UITableView will allow us to do. We’ll load in data from a plist, add some more elements to our table view, including images, subtexts, and allowing editing. These features allow us and the user to customize table views beyond the default appearance. Table views are a very important part of the iOS SDK and are found in many apps; fortunately, they are easy to customize—you can even create your own cells in anyway you’d like!

Open Xcode and create a new Single View application. Call it “AdvancedTables”, set the class prefix to “AT”, Device Family to iPhone, and Use Automatic Reference Counting. Save the project somewhere and create it.

Next, click here to download a file which contains a list of 51 cities and their population. The file is a basic XML-based plist, which is a file type used throughout iOS to store simple data structures like this. Add the file into the Xcode project.

Setting up the View Controller

Open ATViewController.h and have it adopt UITableViewDelegate and UITableViewDataSource. In ATViewController.xib, drag out a Table View from the Library and place it inside the existing view. Control-Drag from the table back to File’s Owner, connecting the table’s data source and delegate outlets.

Next, go to ATViewController.h. Create two strong properties of type NSMutableArray; call them names and populations. In the .m file, synthesize them. We’ll load in data from the plist in the viewDidLoad method:

- (void)viewDidLoad {
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
	NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Cities" ofType:@"plist"];
	NSData *data = [NSData dataWithContentsOfFile:filePath];
	NSPropertyListFormat format;
	NSString *error;
	id fileContents = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
	self.populations = [[fileContents objectForKey:@"City Population"] mutableCopy];
	self.names = [[fileContents objectForKey:@"City Names"] mutableCopy];

Notice that we don’t do any sort of checking on the fileContents result. It would may seem like a good idea to at least check if the dictionary had the two keys; if it only had one, the app would crash when trying to access one or both of them. However, this is a special design consideration. The data source is the driving force of the entire app; it wouldn’t make much sense if some of this data doesn’t exist. We don’t really want the app to continue if the data isn’t valid, so letting it crash might be a good idea in this case.

Next, we implement the data source methods like we did in the last post. Our table will only one section; with a more robust data source such as Core Data, it becomes much easier to implement multiple sections and an index down the side like you’d see in the Music app. For now though, we’ll settle for one section. The number of rows will be determined by the number of elements in either one of the data arrays, as they should correspond—and they do!

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.names count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *cellID = @"CellID";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
	if (!cell) {		// Create new cell
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
		cell.showsReorderControl = YES;
	cell.textLabel.text = [self.names objectAtIndex:indexPath.row];
	cell.detailTextLabel.text = [NSString stringWithFormat:@"Population: %@", [self.populations objectAtIndex:indexPath.row]];
	cell.imageView.image = [UIImage imageNamed:@"CaliforniaIcon.png"];
	cell.imageView.highlightedImage = [UIImage imageNamed:@"CaliforniaIconPressed.png"];
	return cell;

Notably here, we create a cell with a different style, one with a subtitle. The iOS SDK comes with four styles, shown below (click for larger version):

iOS Table View Cell Styles

iOS Table View Cell Styles

The default style doesn’t contain any detail text; nothing will happen if you set the detailTextLabel property.

The showsReorderControl property is a boolean; if true, it will display a reordering control that appears in editing mode. We’ll get into that in a little bit.

Adding an Image to Cells

If you want to add an image to the left of the cell (as with album art in the Music app, or video previews in the YouTube app), it takes very little work. Download the icons and add the following lines within the if (!cell) block:

cell.imageView.image = [UIImage imageNamed:@"CaliforniaIcon.png"];
cell.imageView.highlightedImage = [UIImage imageNamed:@"CaliforniaIconPressed.png"];

The image property is what gets displayed normally; the highlightedImage is swapped in if the cell is highlighted.

If you want the image anywhere else in the cell, you’ll have to create your own cells, which will be a topic for another post—there’s a lot involved!

Editing Table Views

First we’ll need some UI to enable editing. Go into the XIB, lower the top margin of the table view, and drag out a normal Navigation Bar and place it at the top of the view, filling the gap. You can have a navigation bar without a nav controller; in that case, it just becomes an “anchor” of sorts for a few commands. You use nav bars at the top of the screen and toolbars at the bottom. Drag out a Bar Button Item and place it on the left of the nav bar; a “well” will appear as you drag over the location. In the Attributes Inspector, set the Title to “Edit”. Connect the button to a new property called editingToggle. In addition, create an outlet for the table view; call it tableView. Wire it up.

Create a new method called toggleEdit and wire it up to the button. First, we’ll set the table’s editing mode to whatever it’s currently not—if it’s not in editing, make it enter editing mode and vice versa. Then we’ll adjust the button to reflect this change in state. In iOS, the Done button has a different tint; we can use a system-defined parameter rather than having to approximate it with our own.

- (IBAction)toggleEdit:(id)sender {
	[self.mainTable setEditing:!self.mainTable.isEditing animated:YES];
	if (self.mainTable.isEditing) {
		[self.editingToggle setStyle:UIBarButtonItemStyleDone];
		[self.editingToggle setTitle:@"Done"];
	else {
		[self.editingToggle setStyle:UIBarButtonItemStyleBordered];
		[self.editingToggle setTitle:@"Edit"];

Next we implement a few data source methods to allow editing, then to handle the edits.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
	return YES;

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
	return YES;

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
	NSUInteger fromRow = [fromIndexPath row];
	NSUInteger toRow = [toIndexPath row];
	id name = [self.names objectAtIndex:fromRow];
	id pop = [self.populations objectAtIndex:fromRow];
	[self.names removeObjectAtIndex:fromRow];
	[self.populations removeObjectAtIndex:fromRow];
	[self.names insertObject:name atIndex:toRow];
	[self.populations insertObject:pop atIndex:toRow];

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger row = [indexPath row];
	[self.names removeObjectAtIndex:row];
	[self.populations removeObjectAtIndex:row];
	[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

The first two methods tell the table that all the rows can be edited (in this case, deletion is allowed; the alternative is None or Insertion), and that they can be moved. Then we declare the methods that handle the move or delete (in the latter case, it falls under the commitEditingStyle: method). In those methods, we remove (and insert) objects from our backing arrays as necessary.

These edits will remain until the memory is cleared (when the app quits). We’ll look at persistence—saving these changes back to the file—in a later extension.

Other Actions

The UITableViewDelegate declares some methods to support some other actions, including accessory views (views on the side of the cell, which you can wire up to trigger additional actions). Now, we’ll handle the selection, and allow you to put a check mark next to the cell that the user selects.

First, we’ll need to create a new property of type NSIndexPath that will hold the current selection.

@property (strong, nonatomic) NSIndexPath *lastIndexPath;

Next, we need to do some checks in the cellForRow… method—because the method will recycle cells as you scroll, we don’t want the checkmarks to get recycled as well. We check to see if a selection has been made, and if the rows are the same. If they are, then we display the checkmark (this is useful when you scroll back to your selection). Else, we display no checkmark (this is useful if you scroll down or up past your existing selection).

We handle the selection like this:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger row = indexPath.row;
	NSUInteger oldRow = lastIndexPath.row;
	if (oldRow != row) {
		UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath]; 
		newCell.accessoryType = UITableViewCellAccessoryCheckmark;
		UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
		oldCell.accessoryType = UITableViewCellAccessoryNone;
		lastIndexPath = indexPath;
	[tableView deselectRowAtIndexPath:indexPath animated:YES];

If the selections are different, we put a checkmark on the new cell and put nothing on the old cell. If they’re the same, nothing changes. In either case, we deselect the cell to prevent it from being highlighted. Build and run, and you can see the checkmark appearing as you click on each cell.

Row Heights

You can change the height of one or more rows using a simple delegate method:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 88;

The default height is 44; this method would make the cells twice as high.

Indenting Rows

You can control the indent of each row with a delegate method:

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
	return indexPath.row;

This example would create a cascade of cells being indented further with each row. Going beyond a level of 5 or 6 looks really weird, so don’t go too far.

That’s the primary abilities that standard table views can offer. The data source and delegate protocols declare a few other features; we’ll touch upon some of them including sections and the index when we start working with files and persistence.

Download the project here.

The Jungle, Part 5: Table Views and Nav Controllers

Table View Controllers and navigation controllers are two of the most commonly used controllers in the iOS SDK. They require a tweaked way of thinking, but they become much easier to use. We’ll begin with table views.


There exists a stand-alone UITableView, but in many cases UITableViewController simplifies usage of the table view. It handles loading table views from XIBs, reloading data, editing, and implements the data source and delegate protocols. Table views display a list of information, potentially millions of objects long, because of a a clever optimization in the data source methods; usually table view cells can be selected and trigger an action or navigate to another view in a navigation hierarchy. This post will build a table view embedded in a navigation controller, which will allow us to build subviews in a later post.

Data Sources and Delegates

Many UIViews rely on data source protocols to load data. These protocols often ask your controller about sections in your data, and the objects to be displayed within each section. The delegate protocols usually handle selections and editing. The concept can be a bit difficult to grasp at first, but it is one of distinguishing factors of the iOS SDK and really simply your program.

Creating the controller

Open up our application in Xcode. Create a New File. Under Cocoa Touch, select UIViewController subclass. Click Next, and call it GraphicsTableViewController and underneath make it a subclass of UITableViewController. Leave the XIB checkbox checked, and create the file. In the XIB, select the table and open the Attributes Inspector. Notice that you can’t edit the data in the table view from IB; it contains a list of California cities. In the Attributes, the one setting that you will often change is the “Style” drop-down; your options are “Plain” or “Grouped.” Change this to “Grouped.”

Group Table View Appearance

Group Table View Appearance

Save, and go to GraphicsTableViewController.h. Add the following property:

@property (strong, nonatomic) NSDictionary *tableViewData;

Go to the .m file and synthesize this property. In viewDidLoad, populate this dictionary:

self.title = @"Graphics Demo";
NSArray *section1 = [NSArray arrayWithObjects:@"Straight Lines", @"Curves", @"Shapes", nil];
	NSArray *section2 = [NSArray arrayWithObjects:@"Solid Fills", @"Gradient Fills", @"Image & Pattern Fills", nil];
	NSArray *section3 = [NSArray arrayWithObjects:@"Simple Animations", @"Bounce", @"Other Options", nil];
	self.tableViewData = [NSDictionary dictionaryWithObjectsAndKeys:section1, @"Section1", section2, @"Section2", section3, @"Section3", nil];

First, we have to set the view controller’s title so it will display when we create our nav controller. Setting the nav controller’s title does nothing; it uses the title of the visible view controller. Having established the data that we’re going to put into our table view, scroll down to

#pragma mark - Table view data source

A quick way is to use the jump list, where the section will be delineated.

Xcode Jump Lists

Xcode Jump List

In numberOfSectionsInTableView:, return the count of objects in our dictionary and remove the warning:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return [self.tableViewData count];

Here, the data source method is asking for the number of sections in our table, which controls how it gets displayed (where the section headings/breaks are). We return the count (of objects with keys) in our dictionary. Do something similar for numberOfSectionsInTableView:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	id sectionInfo = [self.tableViewData objectForKey:[NSString stringWithFormat:@"Section%d", section + 1]];
	return [(NSArray *)sectionInfo count];

This method asks for the number of elements in a particular section. UITableViews’ sections (and rows) are zero-indexed. We get the corresponding section by incrementing the section by 1, and then return the number of elements in that section.

The next method is where it gets interesting. tableView:cellForRowAtIndexPath: is where you configure each cell in your table; obviously you won’t be actually configuring every single cell, that’s the job of the computer.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		// Common to all cells
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    // Configure individual cells
	id section = [self.tableViewData objectForKey:[NSString stringWithFormat:@"Section%d", indexPath.section + 1]];
	NSString *rowLabel = [section objectAtIndex:indexPath.row];
	cell.textLabel.text = rowLabel;
    return cell;

A lot of the code in this method has already been written out. First, it creates an object—a string in this case—that is an identifier. The next line is where the optimization comes in. Rather than creating new table cells all the time as you scroll (because creating objects is an “expensive” process), the table view dequeues cells as they scroll off-screen. At their default size, about nine cells fit on-screen at a time, so only nine need to be kept in memory. As they get scrolled off-screen, the properties’ values are changed, and it is put back into use. This means that you can have a table with millions of cells, but only nine or fewer have to exist in memory. The code checks to see that a cell exists (for the first few to be created, or if there is an error, there won’t be any cells available to dequeue) and if it doesn’t a new cell is created. Inside the if statement is where you configure settings that you want to be common to all (or a large number of) cells, perhaps including color and style, or some text that you want on all the cells. After creating the cell, we get our section and pull out the label for the row. We then access the textLabel property of the cell and set its text property to the text we just got. We then return the cell.

We need to add one more method to the controller to let it display section headings.

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	switch (section) {
		case 0:
			return @"Lines & Shapes";
		case 1:
			return @"Images & Fills";
		case 2:
			return @"Animations";
			return nil;

This method simply goes through the possible values for section and returns a title accordingly.

That is all you need to get data in a table view. In fact, a simpler table view would not have sections, and could be done using a single array. At this point, however, we have not handled selection. Scroll down a bit further, until you find the method tableView:didSelectRowAtIndexPath:. In the next post, we’ll create a view controller that will be displayed when you select each cell; you can see existing support code for that in the template. However, for now, we’ll just have the cell deselect itself after the selection is made.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

Nothing to it here—once the cell is selected, this delegate method is called. We just deselect the same cell.

Navigation Controllers

Navigation controllers are often used in conjunction with table views to drill down into a hierarchy of information. You can see this in the Settings app on the iPhone (it’s not quite the same on the iPad). Like tab bar controllers, nav controllers are container controllers, in that the majority of their content comes from another view controller. We’ll create a nav controller as part of our tab bar and set our table as its root view controller.

Go into AppDelegate.m and import GraphicsTableViewController.h. Before the creation of the tab bar controller, add the following code:

	GraphicsTableViewController *graphicsTableViewController = [[GraphicsTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
	UINavigationController *graphicsNavController = [[UINavigationController alloc] initWithRootViewController:graphicsTableViewController];
	navController.title = @"Graphics Demo";

Add the nav controller to the tab bar’s array. Now build and run the app, and you’ll see a third tab in the tab bar. Select it, and you’ll see a table view with all the data we’ve configured. Click on a cell to select it; it’ll briefly glow blue before fading again.

In this post we’ve covered the basics of populating table views and nav controllers, two fundamental tenets of the iOS SDK. Download the project here.

The Jungle, Part 4: Automatic Reference Counting

So far, we have been manually doing our memory management according to the basic rules established a long time ago. This method is still fine and is still the standard way to do it, but at WWDC 2011 Apple unveiled the revolutionary ARC technology. ARC stands for Automatic Reference Counting which does exactly what it sounds like—it automates the reference counting steps for you. It follows the exact same rules as the old memory management implementations, just automated for you. Rather than doing a runtime cleanup, as garbage collection does (a process which slows the running of your program at random intervals), the compiler looks at your code and automatically inserts retain, release, and autorelease calls as necessary. In this way, the performance of your application isn’t impacted in the least but it could save you a lot of work—after all, computers were designed to do menial labor like that.

In this post we’ll convert our existing project to ARC. Once we’re there, little work remains in memory management. Basically, ARC frees us from thinking about memory management at all, so upon finishing the conversion process we won’t be dealing with memory management anymore. Let’s get started.

Converting to ARC

Open our project and go to Edit > Refactor > Convert to Objective-C ARC…. You’ll get a sheet that says “Select Targets to Convert”; select the only option the list which should be called “SDK (SDK Demo)”. Then click Precheck. Xcode will build your project then present a new sheet with an introduction.

ARC Conversion Intro Screen

ARC Conversion Intro Screen

Click Next and it’ll say “Generating Preview” for a few moments. The sheet will then expand, providing you with a two column view of your code.

Revisions Editor

Revisions Editor

To the very left you’ll see a list of files. In the main content, the left pane is the new code; the right pane is what you currently have. Changed lines are shaded in blue with a darker blue outline; changed code is highlighted in a salmon-esque color (by default). You can go through the list of files on the left (there should be five) and see the changes that ARC will do for you. You’ll notice that in the properties, retain is replaced by the new keyword strong; in the implementation files dealloc methods are stripped away, as are retain, release, and autorelease calls. The latter methods are now obsolete and you can’t actually call them anymore. Dealloc is not subject to the same treatment, but unless you’re doing some custom cleanup that goes beyond freeing memory, you shouldn’t have your own dealloc. Review the changes, and click Save in the lower-right.

Now Build & Run the app and when it comes in the Simulator you’ll notice that everything works just as before. …And, that’s it! Converting an app to ARC is just that easy. Note though, that in some cases the compiler may encounter cases where it can’t directly convert your code, in which case it’ll issue an error which you will have to address before you can run your app. This is often the case with files you might receive as part of someone else’s code library. In those cases, it is usually best to allow the original developer to support ARC or not as necessary. For the time being though, you can turn off ARC on a per-file basis to suppress those errors and run the code with the existing memory management code.

Selectively Turning Off ARC

To do so, select the Top Level project in the File Navigator, and select the name of your Target in the pane immediately to the right. Then in the main content pane, select Build Phases from the top, and expand the disclosure triangle next to “Compile Sources”.

Disable ARC per file by going to Build Phases > Compile Sources

Disable ARC per-file here

Select one or more files that you wish to exclude from ARC, and then hit Return on the keyboard. A little text field will appear. Inside that field, type


Which is a compiler flag to turn off ARC for those files. Hit Done and you’ll see the flag appear next to the files you’ve selected.


ARC code is fully supported in iOS 5, as well as OS X 10.7 Lion. In addition, most of ARC (exceptions detailed below) is supported in iOS 4 and OS X 10.6 Snow Leopard.

Language Changes

Converting a simple app like ours to ARC is not difficult. But ARC adds and modifies more of the Objective-C language, and these changes are worth talking about.

Autorelease Pools

Before ARC, you created autorelease pools like any other object and drained them when you’re done. However, because autorelease is no longer supported by the language, the old method wouldn’t work very well. So a new method had to be devised. Take a look at main.m, in the Supporting Files group. You’ll see code like this:

@autoreleasepool {
	    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

There now exists a brace-delineated block for autorelease pools. All objects created within the block are autoreleased; the exact moment of autorelease is still determined by the ARC system. Therefore, in cases when you need to create an autorelease pool and release it independently from the main one (perhaps in a tight loop where you’re creating many autoreleased objects), just enclose the entire loop in the new block.

New Keywords

In our conversion process, retain was replaced by strong. This makes sense, as retain is no longer available. strong means the same thing—it states it is a strong relationship, that the class owns (and should “retain”) the property. Its counterpart is weak, which means that it is a weak reference. This is especially important when you have a loop reference—for example, if you have a chess game, then you might have a Grid class which keeps track of many Pieces , but at the same time each Piece has a reference back to its owning Grid. In such a case, if the references in both directions were strong, then neither object could be released because they’d both have a +1 retain count to each other, and you’ll leak the memory. A weak reference prevents this issue because it does not actually increment the retain count.

Note though that weak references are only supported on iOS 5 and OS X Lion. In previous versions, you’ll have to use unsafe_unretained, which is a more general keyword that offers you less “protection” by the compiler. It also maintains a weak reference, but it doesn’t guarantee anything else; therefore, you have to make sure that the value is valid when you access it to prevent bad access errors.

If you want to declare ivars with the same characteristics (and you should, just to be clear and to help the compiler out), prefix the keywords with two underscores:

__strong, __weak, __unsafe_unretained

Minor Issues

In my experiences I’ve come across two anomalies when using ARC:

  • If you are using a switch statement and you are declaring a new local variable as the first line of each case, you’ll have to surround each case with curly braces immediately after the colon and after the break; or you’ll get a warning about the variable being out of scope.
  • There may be presentation issues with UIPopoverController on the iPad, where the application may crash with the error that the popover had been released before the popover had been dismissed. I will continue to investigate this issue and file a bug report with Apple if necessary. For the moment, a solution seems to be to create a strong property for it to always keep a reference to it.

ARC greatly simplifies app development on Apple platforms and allows it to catch up to other languages with garbage collection, without the overhead imparted by garbage collection (which is in fact significant on a mobile device like the iPhone; even desktop OS X apps rarely use GC). There are more obscure aspects of ARC than I’ve covered here, including bridged casting which you might see if you start working with C code or some lower-level Foundation and Core Foundation classes. I’ll talk about them as we come to them. If you’re curious, feel free to check out the official ARC documentation.

And as usual, download the newest version of the project here.

The Jungle, Part 3: Flipping and Tab Bars

In previous tutorials we’ve been using some basic UIKit elements on standard views. Today, we’re going to add a tab bar to our application and wire it up; it’ll pave the way for some more compelling future expansions. Tab bars are more involved than the regular views we’ve been using; in additional to simply setting and accessing properties, we also have to contend with a specific controller and design pattern, as well as delegates. Let’s get started.

Tab Bar Controllers

In most cases, tab bars are used with UITabBarController. You may use an independent tab bar if you’re using it to display the same information in the same view, just sorted differently, for example. However, if you plan on swapping views around, you should use the controller because it manages the swapping mechanism and paradigms for you.

According to Apple’s documentation, “The UITabBarController class implements a specialized view controller that manages a radio-style selection interface.…[Y]ou use instances of it as-is to present an interface that allows the user to choose between different modes of operation. This tab bar interface displays tabs at the bottom of the window for selecting between the different modes and for displaying the views for that mode.” Tab bars are prevalent in many of the standard iOS apps, including Clock and Music.

Rather than accessing the tab bar itself (Apple claims that “You should never access the tab bar view of a tab bar controller directly”), you should pass the tab bar controller an array of UIViewControllers (or subclasses of it) to a property called viewControllers. The ordering in the array determines the order of the tabs. Alternatively, you can configure the tabs’ order, title and icon in Interface Builder. When a tab is selected, the controller will load the root view controller for the corresponding tab in the main content view. This means that if you’ve drilled into a navigation stack (which we will be covering in a future post), you will be returned back to the top of the stack, even if you tap the tab you’re currently on. By default the state of the view is not saved; however, you can do initial configuration in your own controllers to do so. Any class can become the delegate of the tab bar and receive notifications about changes. As per the nature of delegation, this is completely optional; proper configuration in Interface Builder means that the view swapping will work fine without having to create a delegate.

Getting Started

Today we’ll be creating a second view controller to have something to switch to, and then we’ll create a tab bar controller and implement the switching. The process is really intuitive once you know where to begin—so let’s begin!

Begin by creating a New File in Xcode. Make sure UIViewController subclass is selected in the Template pane and click Next.

New UIViewController Subclass File

The Class name should be FlipViewController. It should be a Subclass of UIViewController, not be targeted for iPad, and have a XIB for the user interface. Click Next, and then Create (unless you want to change the file save location or the group the new files get placed under—go ahead). You’ll get three new files—FlipViewController.h, FlipViewController.m, and FlipViewController.xib. Here, we’ll create a very simple view that implements a flip-over view like you might see in the Weather or Stocks app.

Start by creating two UIViews in the header, making sure to declare them as IBOutlets and calling them frontView and backView. In the XIB, drag out two UIViews from the Library. Connect the views—Control drag from the File’s Owner (the first icon on the strip to the left) down to the views and make the connections as you’re used to. In the view you’ve designated to be the front, choose a dark color for the Background and then drag out a UIButton. In the Attributes Inspector, next to Type, select Info Light to get you the little “i” button that you’ve seen around iOS. Align that with the bottom right corner of the view. Also in each view, add a label with “Front view” and “Back view”, just for reference. In your back view, add a regular UIButton in the upper left corner with the text “Done”. This follows the standard UI design pattern—if you’re using an info button to go to another view, the info button should be in the lower-right corner; a Done button to return sometimes may be in a nav bar (which we’ll cover in a later post), but is usually in the upper-left corner.

Now connect the actions. The method to go to the back view should be called flipToBack: and take a sender. The method to go back should be called flipToFront: and also take a sender. Of course, make sure the methods are defined in the header, save both the header and the XIB, and go to the .m file. Synthesize the frontView and backView. Add the following line to viewDidLoad after the existing code:

[self.view addSubview:self.frontView];

This will make the frontView visible. Next we’ll implement the flipping methods:

- (IBAction)flipToBack:(id)sender {
	[UIView transitionFromView:self.frontView toView:self.backView
			   options:(UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionTransitionFlipFromRight)

- (IBAction)flipToFront:(id)sender {
	[UIView transitionFromView:self.backView toView:self.frontView
			   options:(UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionTransitionFlipFromLeft)

These methods are rather similar. We’re calling new UIView animation methods introduced with iOS 4 that replaced a more verbose and complicated system from before; these methods also take advantage of blocks which were also new with iOS 4 and, again, will be covered in the future. Here, we’re asking it to transition from one view to another. It’ll draw one view, and then animate in the other based on the options you pass in. The duration is the length of the time you want the animation to take. The options are a list of options (at the end of the page) you can pass in; you can combine them any way you want (barring conflicting options) using the bitwise OR operator ( | ) and enclosing the group in parentheses. Here, we’re telling the animation to use a smooth, natural ease-in and then ease-out at the end. Other options include a linear path, or just ease-in or just ease-out. Finally, you can pass a block in when the animation completes; we’re not going to do anything here for the moment. Our view controller is done—so let’s build our tab bar controller.

Creating the Tab Bar Controller

Open AppDelegate.h and add a tab bar controller property:

@property (nonatomic, retain) UITabBarController *tabBarController;

Synthesize the property. In the implementation, import FlipViewController.h and then release tabBarController in the dealloc method. Then create the tab bar controller:

RootViewController *rootViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
rootViewController.title = @"Root View Controller";
FlipViewController *flipViewController = [[FlipViewController alloc] initWithNibName:@"FlipViewController" bundle:nil];
flipViewController.title = @"Flip View Controller";
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:rootViewController, flipViewController, nil];
self.window.rootViewController = self.tabBarController;

First we create the view controllers and set their title. The title of the view controllers is the title that the tab bar displays. We then create a tab bar controller and set the view controllers as an array. You then set the root view controller as before.

If you run the program now, you’ll get a working app with a tab bar at the bottom. Switch between the tabs and go to the Flip View Controller—and you’ll realize the issue we have. The tab bar is in fact obscuring the flip button. The solution is rather simple—go to FlipViewController.xib.

Simulated Tab Bar & Moved Button

Select the front view and move up the Info button. Select the front view itself and go to the Attributes Inspector. Under Simulated Metrics, select Tab Bar from the list next to Bottom Bar. Using that as a guide, position the info button. Build and run again. The flip view will work as you’ve seen in other Apple apps.

Apple’s Progression

In iOS 5, Apple’s recommended way to create controllers is through code in the App Delegate. In previous versions you’d have started with a MainWindow.xib which you can configure in Interface Builder. I feel that because from now on all project templates will feature this new code, it is important to get to know it.

You can download the current iteration of the file here.

The Jungle, Part 2: More UI Elements

This week we’re going to continue from Part 1 and explore additional UI elements. Before we begin though, a bit of (old) news—iOS 5.0 was released on Wednesday, and with it Xcode 4.2. As such, from now on I will be working with Xcode 4.2 and the 5.0 SDK. Once we get the basics down we can discuss compatibility with older versions and how to check the system version, but we’ll use the newest and greatest for now.

As usual, Xcode 4.2 is available on the App Store. The Xcode 4.2 build is 4D199 (you’d be surprised how difficult it was to find that anywhere else—important if you’re upgrading from a Developer Preview), which you can get either from the Welcome screen or by going to Xcode > About Xcode. There is an installation issue floating around in which you may be constantly installing 4.1. In that case, I’d recommend uninstalling Xcode first, and then running the “Install” that the App Store downloads. That fixed the problem for me.

Once Xcode is installed, open up the project from last time, and dive into RootViewController.xib.

Interface First

With Xcode 4’s integration of Interface Builder and the code, it breaks down the boundaries of code versus interface and allows you to easily jump back and forth as ideas come into your head. This time, we’ll put together the interface first and then hook it up to code—even to code that doesn’t exist yet.

First, start by moving the text field up a bit so we have some more vertical room below. Drag it up, following the blue guidelines, until it snaps into place a bit below the button.

Segmented Control Settings

Segmented Control Properties

Drag out a Segmented Control and place it near the middle of the screen. Extend the width until you get to the blue guidelines at the left and right of the screen. Go to the Attributes Inspector, and use the Segment pop-up menu to select “Segment 0 – First”. Underneath, change the Title to “Colors” and watch the change propagate to the UI as well. Change the title of the second segment to “Progress” using the pop-up to change the segment.

The segmented control works similar to the tabs you see across OS X, especially in System Preferences—users expect them to “swap” view content to something else, and they are usually placed above the content that you expect to swap. For simpler views it may be easy enough to place views overlapping each other and hide or show them as necessary (UIView has a hidden property that can be set to YES or NO). However, this is quite cumbersome and doesn’t scale very well. A better alternative is to create a plain UIView and set that to individual views as necessary. Therefore, drag out a basic UIView, align it underneath the segmented control, make it as wide, and drag it down until the blue guidelines appear at the bottom. It should look like this:

Main View

New Main View

Now select the view, and copy (Command-C) it. Click outside of the main view (on the main canvas area) and paste (Command-V). You should get a blank view the size of the original, floating around on the canvas. Click on the canvas again, and paste another view. They will be the views you’ll swap in with the segmented control.

Set the background of both views to Group Table View Background Color. It may be easier to set their color to transparent, but this has a major impact on drawing performance—it is much faster to set a specific opaque color.

Drag out UI elements from the Library to build two views like you see here. The exact positioning doesn’t matter, but make sure to get the correct elements. The first view contains a standard UIView at the top with the Background color set to 50% gray (click on the left part of the Background control in the inspector to get the standard OS X color picker). Underneath are four labels, right-aligned with a standard shadow (most UI text in iOS is drawn with a shadow) and four sliders next to the labels. Here, don’t worry about the edge guidelines—go right up to the edge of the view. You’ve already accounted for the edge guides in the main view.

Sliders View

Sliders View

The second view contains a few more elements—a bold-font label, a regular-font label, a stepper control (new in iOS 5), another bold-font label, a switch, a progress view, and a button. None of the views except the labels have been customized away from their default appearance. The regular label should have its text set to 0%, rather than the standard “Label”.

Progress View

Progress View

We have to set some properties on the stepper for it to work with us. Select it then open the Utilities Inspector. The Minimum value should stay at 0 but the Maximum should go up to 100. Increase the Step to 10 to have it change by 10, from 0 to to 100. Also, select the progress view and set the Progress to 0.

Making Connections

Our interface design is now done, so let’s make the connections. Open the Assistant editor (The second button in the “Editor” group in the toolbar). Make sure the file in the right pane is RootViewController.h (you can use the jump bar). Control-drag from the blank view in the main view to a blank line in your header. You’ll get a gray rectangle that says “Insert Outlet or Outlet Collection”.

New Connection

New Connection

Let go, and you get a little popup that lets you configure the outlet name and type. Call the outlet sectionView. Click Connect, and a new property will appear with a blue flash. To connect the other smaller views, you’ll have to Control-drag from the icons on the left edge of the IB view to the code. See screenshot below:

Connection from Sidebar

Connection from Sidebar

The view with the sliders should be called colorsView; the other should be called progressView.

New Outlet Popup

New Outlet Popup

Then, connect all five elements in the colorsView to the header as well—displayColor, redSlider, greenSlider, blueSlider, and alphaSlider. The progressView isn’t quite as straight-forward, but it’s not difficult. Connect the label next to “Fill:” as amountLabel, the stepper as amountStepper, the switch as animatedSwitch, and the progress view as progressIndicator.

Now we’ll connect the actions. Start off with one of the sliders—right click on one of them, and scroll down until you find the Value Changed Event.

Control Events

Control Events

Click and drag from the circle to the right until you come to a new line underneath the actions—you’ll get a blue line you’ll be familiar with now. You’ll get the gray rectangle that says “Insert Action” this time. In the pop-up, call the method colorSliderChanged. Next to Arguments, select “None” from the menu. Click Connect. Now do the same with the other sliders, but rather than dragging to a new line, drag until the colorSliderChanged method becomes highlighted. You’ll connect to that method, rather than creating a new one.

We’ll use a slightly different way to connect the button’s action. Control-drag from the “Reset” button to a new line underneath the actions. The default option will connect an outlet, but we want an action. From the Connections popup menu, choose Action instead. Change the name to resetContent.

New Action Popup

New Action Popup

Note that the event is “Touch Up Inside”, the default for buttons. Arguments should again be None.

Connect the stepper control in the same way. Name should be fillAmountChanged; Arguments should be None. Note the default event, “Value Changed” for the segmented control. Arguments should be None.

Finally, we’ll have to connect the segmented control as well. Follow the same process as before. The name should be sectionChanged. Arguments should be Sender.

Writing the Code

Open RootViewController.m and scroll through the file. You’ll note a bunch of synthesized properties, ivars added to the dealloc method, and blank methods for all the actions you just connected. This saves us a lot of boilerplate code and lets us get right down to work. Put in a blank line in the colorSliderChanged method after the opening brace. This method will change the fill color of that gray rectangle based on the slider values, converting to an RGB-A color. Note though that this isn’t necessarily a recommended way to do it—it can be slow on older devices.

We’ll create four float variables to hold the values of the sliders, then create a UIColor instance based off the floats. Then we assign that as the background color of the blank view. The code for the method:

- (IBAction)colorSliderChanged {
	float redColor = self.redSlider.value;
	float greenColor = self.greenSlider.value;
	float blueColor = self.blueSlider.value;
	float alphaValue = self.alphaSlider.value;
	UIColor *newBackground = [UIColor colorWithRed:redColor green:greenColor blue:blueColor alpha:alphaValue];
	self.displayColor.backgroundColor = newBackground;

Next, let’s handle the case where the stepper’s value is changed. First we need to update the label, which we’ve already connected. We grab the stepper’s value, and create a string out of that. Then we assign the string to the label’s text property. Next, we’ll update the progress bar. We use the switch’s on property to determine if we should animate, and use the stepper’s value to determine where to fill to.

- (IBAction)fillAmountChanged {
	NSInteger amount = (NSInteger)self.amountStepper.value;
	// You need two percents to "escape" it and actually display a percent sign
	NSString *amountString = [NSString stringWithFormat:@"%d%%", amount];
	self.amountLabel.text = amountString;
	[self.progressIndicator setProgress:((float)amount / 100.0) animated:self.animatedSwitch.on];

The reset method is easy. We’re just assigning some properties.

- (IBAction)resetContent:(id)sender {
	self.amountStepper.value = 0.0;
	self.amountLabel.text = @"0%";
	[self.animatedSwitch setOn:YES animated:YES];
	[self.progressIndicator setProgress:0.0 animated:YES];

There’s one last bit that we have to handle—view swapping. Right now if you run the project you’ll just get a white rectangle on screen and you’ll not get any of our new code. A simple method like this will fix the issue:

- (IBAction)sectionChanged:(id)sender {
	UISegmentedControl *sectionControl = (UISegmentedControl *)sender;
	if (sectionControl.selectedSegmentIndex == 0)		// Colors section
		[self.sectionView addSubview:self.colorsView];
	else if (sectionControl.selectedSegmentIndex == 1)	// Progress section
		[self.sectionView addSubview:self.progressView];

In this method, we’re simply adding the correct view to our main placeholder view as necessary.

Now the code is complete. But if you run it, you’ll see an obvious problem—the first time you run, you’ll get a blank white rectangle. It’s only when you select a segment in the segmented control that you get a view. Let’s fix that by adding this one line to viewDidLoad:

[self.sectionView addSubview:self.colorsView];

We know that the first view to load will be the colors view, so automatically we’ll add that view. If you build and run now, you’ll get the fully working app.

UIKit From Here

As you’ve seen, using UIKit controls is rarely very difficult or involved. 85% of the time you’re just setting and getting properties on the controls. Some of them have a custom setter that allows you to animate the change. There are some other controls that we haven’t really covered, but they’re not difficult. We’ll get into putting a tab bar into our application (and its corresponding controller) next time. For now though, if you would like to experiment around, feel free. Also check out Apple’s documentation. You can download this version of the sample project here.

  • Welcome

    My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

  • Contact Me

    If you need to contact me for any reason, feel free to send me an email.
  • The Giving Spirit

    If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 220 other followers

  • Back to the Past

    July 2020
    S M T W T F S
  • Time Machine

  • You count!

  • Worldwide Stats

    free counters
%d bloggers like this: