Advertisements

Working With Web Data


Apps become a lot more interesting when we connect them to the internet. They’re able to fetch live data, update that data, and interact with other people and devices. In this post, we’ll look at how to pull data from the internet.

We’ll be working with JSON data. JSON, which stands for JavaScript Object Notation, is one of two popular formats for reading general data from the web (XML is the other). JSON has the advantage of being a lot more terse than XML, and is a lot easier for websites themselves to work with. iOS includes libraries to work with both data types.

Let’s begin by creating a new project—I’ll call it JSONRead—and making our main view controller a subcontroller of UITableViewController. We’ll begin by reading JSON data from the web, parsing it, and saving it to a data object in our controller. In fact, here is the JSON we’ll be using (see below for more on the JSON syntax and how to generate it):

[
    {
        "fname": "Nadene",
        "lname": "Feehan",
        "email": "nadene.feehan@gmail.com",
        "phone": "(152) 555-5321"
    },
    {
        "fname": "Marleen",
        "lname": "Harding",
        "email": "marleen@mharding.com",
        "phone": "(134) 555-1134"
    },
    {
        "fname": "Moon",
        "lname": "Larusso",
        "email": "lunarguy@hotmail.com",
        "phone": "(123) 456-5432"
    },
    {
        "fname": "Scotty",
        "lname": "Wollman",
        "email": [
            "scotty@wollman.com",
            "beammeup@gmail.com",
            "s.wollman@bigcorp.com"
        ],
        "phone": "(152) 555-5321"
    },
    {
        "fname": "Celest",
        "lname": "Feehan",
        "email": "celestial@gmail.com",
        "phone": "(098) 765-4321"
    },
    {
        "fname": "Saggarth",
        "lname": "Ramakristhan",
        "email": "sagar@gmail.com",
        "phone": "(012) 345-4321"
    }
]

Next, in the .m file, we’ll define a link to the file, and a private interface to hold our properties:

#define JSON_FILE_URL @"https://dl.dropboxusercontent.com/u/7828009/JSONRead.json"

@interface PeopleListViewController ()
@property (strong, nonatomic) NSArray *names;
@property (strong, nonatomic) NSArray *data;
@end

Synthesize these properties. Next, we’ll load the data and parse it into basic data types in viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = @"JSONRead";
	
	// Download JSON
	NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:JSON_FILE_URL]];
	// Parse JSON
	NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
	self.data = jsonResult;
	NSMutableArray *_names = [NSMutableArray array];
	for (id item in jsonResult)
		[_names addObject:[NSString stringWithFormat:@"%@ %@", item[@"fname"], item[@"lname"]]];
	self.names = _names;
}

Downloading data from the internet starts by creating an NSURL (which can be instantiated from an NSString), then getting an instance of NSData from that URL. We then use a method that Apple has provided since iOS 5.0 to parse the JSON. Note that we’re casting to NSArray—NSDictionary is another common option, and we’ll talk about how to tell which to use below. Finally, we simply loop through each element in the array, and pull out certain properties to generate an array of names, which we display in our table view. In this case, each element in the parsed array is a dictionary, so we’re using the new literal syntax to access a key-value pair in each item.

Our table view data source is pretty simple—one section, with as many rows as we have names. Our table view cells display the names that correspond to the indexPath.row, and in the delegate, when you select a cell we create a detail view controller (make sure to import the header), pass in the item from our data array that corresponds to the selected indexPath.row, and push the detail view controller onto the navigation stack.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.names count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    cell.textLabel.text = self.names[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	PeopleDetailsViewController *detailViewController = [[PeopleDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped];
	detailViewController.details = self.data[indexPath.row];
	[self.navigationController pushViewController:detailViewController animated:YES];
}

JSON Format

JSON begins with key-value pairs:

"fname": "Nadene"

These values can be an integer or floating point, string, boolean (true or false), array, object, or null. A list of key-value pairs is separated by a comma.

JSON values can be an array—a list of values (any of the above values are valid in an array) wrapped in square brackets. Our JSON sample is in fact a single array, as shown by the starting and ending brackets, and this knowledge allows us to choose NSArray as the object that the JSON gets parsed to.

JSON values can also be an object (objects in a Javascript context), which is rather like a grouped set of key-value pairs, wrapped in curly braces. Groups are used in our sample JSON to group the key-value pairs of each person as a separate element inside the array.

So for our sample JSON, we have a single array containing six objects. Each object has four key-value pairs, and for Scotty, he has an array for his email addresses, signifying that he has multiple emails.

Detail view

The details view controller is also a subclass of UITableViewController, with an NSDictionary for the details which we pass in:

@interface PeopleDetailsViewController : UITableViewController
@property (strong, nonatomic) NSDictionary *details;
@end

We define a simple method to generate a name based on the person’s first name and last name

- (NSString *)name {
	return [NSString stringWithFormat:@"%@ %@", self.details[@"fname"], self.details[@"lname"]];
}

and use it to set the title in viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = [self name];
}

Our table view data source is, again, pretty simple—1 section, 3 rows, and specific content for each row:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (!cell)
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    
    switch (indexPath.row) {
		case 0:
			cell.textLabel.text = [self name];
			cell.detailTextLabel.text = @"Name";
			break;
		case 1: {
			NSString *email = [details objectForKey:@"email"];
			if (!email)
				email = @"No email";
			if ([email isKindOfClass:[NSArray class]])
				email = @"<Multiple emails>";
			cell.textLabel.text = email;
			cell.detailTextLabel.text = @"Email";
			break;
		}
		case 2:
			cell.textLabel.text = self.details[@"phone"];
			cell.detailTextLabel.text = @"Phone";
			break;
		default:
			break;
	}
    
    return cell;
}

This is all the code we need. Click Run, and we’ll see a simple contact manager.

Contacts—People List

Contacts—People List

Contacts—Detail View

Contacts—Detail View

Generating JSON

A JSON string is valid Javascript syntax, so it can be used as a Javascript object or array. To turn a string into Javascript, use JSON.parse(text, function(key, value)); to convert an object into a JSON string, use JSON.stringify(object). jQuery also allows you to serialize() a form, which you can then pass to a server. This is really useful when you want to submit a form via AJAX.

In Ruby, the new hash notation is the same as JSON, which makes things easier. object.to_json will create a JSON string out of an object, and JSON.parse(object) will create an object from JSON.

In PHP, json_encode() takes an object or array (linear or associative) and returns a JSON string. json_decode() will return an object or linear array depending on the JSON; an optional second parameter allows you to force an associative array where it would otherwise return an object.

Download project files

Advertisements

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 colorWithRed:self.red green:self.green blue:self.blue 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];
	newColor.red = [self randomColorComponentValue];
	newColor.green = [self randomColorComponentValue];
	newColor.blue = [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 = currentColor.name;
	cell.detailTextLabel.text = [NSString stringWithFormat:@"Red: %.3f Green: %.3f Blue: %.3f", currentColor.red, currentColor.green, currentColor.blue];
	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.color.name;
	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.color.name = 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.

The Jungle, Part 7: Quartz Demos (Section 3 of 3)


In this last section, we will combine the drawing abilities of Quartz with the blazing fast animations that are provided by Core Animation.

Core Animation Primer

Core Animation is a framework for animating a number of properties on views. It was introduced with OS X 10.5 (Leopard) and iPhone OS 3.0. Animation is important because it conveys visual feedback , especially in state change. For example, zooming in on OS X and iOS is an animated process, rather than jumping from one zoom level to another. This shows what happened, rather than providing a visual disconnect. Core Animation handles the animation implicitly, which means that, if you choose to accept the default options, you can simply set a property and the transition will be animated. Of course, you can also have fine-grained control of the animation.

Core Animation animations are fully GPU-backed and coded through OpenGL. This allows the animations to be incredibly fast—the original iPhone could hit 30fps on UI animations while Windows XP and earlier versions of Android performed all the animation code in the CPU, which is a significant performance bottleneck (the benefits of hardware accelerated graphics).

Core Animation exists as a backing layer behind your views. The layer is a cached copy of the view stored in the graphics card. It propagates down a view hierarchy—subviews of a view are automatically backed, but parent views are not automatically backed. It might be easiest to back the topmost view, but because each layer is stored in video memory (which may be shared with the main system memory), it is best to minimize your memory footprint. Back only the layers you need to animate.

Core Animation allows you to perform some styling options that are much simpler than using Quartz. For example, you can take an image, apply a styled border, round the corners, and put a drop shadow underneath—and animate all of it, using a few lines of Core Animation code.

Let’s get started.

General-Purpose Drawing with Core Animation

Open up CustomView.m in our sample project, and go to drawOtherInContext:. First we’ll look at how to draw a rounded rectangle in Quartz. This uses a method introduced with the iPad in iOS 3.2; it was not available on the iPhone until iOS 4.2, seven months later; Core Animation was introduced in iOS 3.0.

First, make sure to import QuartzCore.h in CustomView.h:

#import <QuartzCore/QuartzCore.h>

The Quartz code:

UIBezierPath *roundedRectQuartz = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(10, 10, 70, 90) cornerRadius:8.0];
	[[UIColor orangeColor] setFill];
	[roundedRectQuartz fill];

The Core Animation code:

UIView *roundedRectView = [[UIView alloc] initWithFrame:CGRectMake(90, 10, 70, 90)];
	roundedRectView.backgroundColor = [UIColor orangeColor];
	roundedRectView.layer.cornerRadius = 8.0;
	[self addSubview:roundedRectView];

Although the Core Animation code is actually a line longer, you get to work with standard UIKit interfaces; in fact, you could perform CA-type drawing on existing UIView elements (like buttons and text fields) without having to subclass them (remember that Quartz runs through the drawRect: method, so you’d have to subclass to use Quartz). The line of interest is the third one, where we access the layer property on the newly created view. This layer is a reference to a CALayer, the class the represents the CA backing layer. The cornerRadius is a built-in property of the class.

You can manipulate CALayers as you would UIViews. So you can create another layer and add it to your existing layer:

CALayer *shadowBox = [CALayer layer];
	shadowBox.backgroundColor = [UIColor purpleColor].CGColor;
	shadowBox.shadowColor = [UIColor blackColor].CGColor;
	shadowBox.shadowRadius = 1.0;
	shadowBox.shadowOpacity = 0.3;
	shadowBox.shadowOffset = CGSizeMake(1.0, -2.0);
	shadowBox.frame = CGRectMake(120, 30, 20, 30);
	[self.layer addSublayer:shadowBox];

The results are exactly what you expect, but using easy Objective-C rather than C.

Finally, we’ll play around with an image:

CALayer *imageBox = [CALayer layer];
	imageBox.backgroundColor = [UIColor blackColor].CGColor;
	imageBox.borderColor = [UIColor whiteColor].CGColor;
	imageBox.borderWidth = 3.0;
	imageBox.cornerRadius = 10.0;
	imageBox.shadowColor = [UIColor blackColor].CGColor;
	imageBox.shadowRadius = 3.0;
	imageBox.shadowOpacity = 0.8;
	imageBox.shadowOffset = CGSizeMake(2.0, 2.0);
	imageBox.frame = CGRectMake(180, 10, 102, 64);
	CALayer *imageLayer = [CALayer layer];
	imageLayer.contents = (id)[UIImage imageNamed:@"Image Fill.jpg"].CGImage;
	imageLayer.cornerRadius = 10.0;
	imageLayer.masksToBounds = YES;
	imageLayer.frame = imageBox.bounds;
	[imageBox addSublayer:imageLayer];
	[self.layer addSublayer:imageBox];

Here, we actually need to create two layers. To force the image to have rounded corners (by default it’ll draw the image regardless of the corners), you need to set the masksToBounds property to YES. This, however, prevents the shadow from being drawn, as the shadow is outside of the bounds. Therefore, you need a second layer to hold the image; the first will contain the border and shadow.

you can also perform Quartz-like custom drawing with CALayers as well. You need to set a delegate for the layer; the delegate must implement drawLayer:inContext:, which is analogous to drawRect:. You then call setNeedsDisplay on the layer, which works just as it does with UIViews.

Animating with Core Animation

Let’s look at a quick example:

CALayer *pulsingBox = [CALayer layer];
	pulsingBox.backgroundColor = [UIColor whiteColor].CGColor;
	pulsingBox.borderColor = [UIColor blackColor].CGColor;
	pulsingBox.borderWidth = 2.0;
	pulsingBox.cornerRadius = 5.0;
	pulsingBox.frame = CGRectMake(10, 10, 80, 50);
	CABasicAnimation *pulsingAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
	pulsingAnimation.toValue = (__bridge id)([UIColor orangeColor].CGColor);
	pulsingAnimation.duration = 3;
	pulsingAnimation.repeatCount = 10;
	pulsingAnimation.autoreverses = YES;
	[pulsingBox addAnimation:pulsingAnimation forKey:@"backgroundColorPulse"];
	[self.layer addSublayer:pulsingBox];

Here we create a CALayer as before. Then we create an instance of CABasicAnimation, which allows us to animate the value of a key path. We want this to pulse, so we only need to set an ending value; setting a starting value is usually redundant anyway. The (bridge id) bit is simply an ARC-specific cast of a struct type to id. We set the duration of the animation, a repeat count, and have it automatically reverse, which gives the pulse we’re looking for. We then add the animation to the layer, which implicitly causes it to start animating. The addAnimation:forKey: method takes a string as its second argument; this is the string that is used to identify the animation. To stop the animation before it’s finished, you call removeAnimationForKey:, using the same key. You can also send removeAllAnimations to stop all animations for a layer.

In this way, you can only animate one property at a time. You can combine multiple CAAnimation objects in a CAAnimationGroup object, which contains an array of CAAnimations. You then set the animation group as the animation on a layer, and all the properties animate. This is useful for setting the timing on a group; the timing of animations within the group are clipped to the timing of the group.

Motion Paths and Repetition

You can create much more complicated animations using keyframes. Keyframes are locations in the animation where you explicitely set the values of certain parameters, and the animation system will calculate all the intermediate steps based on the animation properties and the start and end values. In Core Animation, this is represented by CAKeyframeAnimation.

CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath: @"position"];
bounceAnimation.removedOnCompletion = YES;
bounceAnimation.fillMode = kCAFillModeForwards;
bounceAnimation.duration = 5;
bounceAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

We create our animation, tell it to remove itself after it’s done (to reduce processing and memory usage), retain the final position after it’s done (that’s what the fillMode specifies), make it take 5 seconds, and accelerate at the start and decelerate at the end.

Next, we have to define the path for the animation to follow (since we are animating the position). We create a mutable path object and draw to that, just as we would to a context. However, the functions we use have “path” in their names, rather than “context”. Finally, we assign the path to the animation.

CGMutablePathRef bouncePath = CGPathCreateMutable();
	CGPathMoveToPoint(bouncePath, NULL, 0, 120);
	CGPathAddArc(bouncePath, NULL, 0, 180, 60, 0.5*M_PI, 0, 0);
	CGPathAddArc(bouncePath, NULL, 120, 180, 60, M_PI, 0, 0);
	CGPathAddArc(bouncePath, NULL, 240, 180, 60, M_PI, 0, 0);
* 	CGPathAddArc(bouncePath, NULL, 360, 180, 60, M_PI, 0, 0);
	[bounceAnimation setPath:bouncePath];

Finally, we create a view to animate, and add the animation to the view.

UIView *animatingView = [[UIView alloc] initWithFrame:CGRectMake(0, 90, 48, 60)];
	animatingView.backgroundColor = [UIColor redColor];
	[self addSubview:animatingView];
	[animatingView.layer addAnimation:bounceAnimation forKey:nil];

We’ve gotten the view to animate, following a crazy path that we’ve defined. You’ll note that it’s not very smooth…but that comes down to the timing function. You can adjust the timing function just as you could the position of colors in a gradient. But that’s a topic for another time.

Sorry for the lack of images in this post: I lost a lot of data when a power surge knocked out my computer and much of my backup as well. All the screenshots I had were lost. But here’s the code from this project, so you can build and run at your leisure.

Download here

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 7: Quartz Demos (Section 2 of 3)


This section will continue from where we left off last week. We’ll work with solid fills, gradient fills, and image and pattern fills. Open up the project from last week, and let’s get started. Navigate to CustomView.m

Single Color Fills

In the last section we filled our paths with solid fill colors. In those cases, we started with a color defined with UIColor. In some cases, however, you may want more control. Quartz’s underlying color structure is represented using a data type called CGColorRef (sometimes abbreviated to CGColor). You can create a UIColor with a CGColor and vice versa. UIColor has the

+colorWithCGColor:

method, and instances of UIColor have a .CGColor property. For example, to create a CGColor that represents a bright aqua color, we could use this code:

[UIColor colorWithRed:0 green:0.5 blue:1].CGColor;

To fill a rectangle with this color, we could use the following code:

CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0 green:0.5 blue:1 alpha:1].CGColor);
CGContextFillRect(context, CGRectMake(20, 30, 80, 100));

Remember the state-based nature of Quartz—You set a color, or a certain style, then use it. We set a fill color, then use it to paint a rectangle using CGContextFillRect(). There is also CGContextStrokeRect().

That’s really all there is to single-color fills. You set a color, and then you fill a shape or path.

Gradient Fills

A gradient fill is a fill for a shape that transitions through two or more colors. Most gradient fills are linear, where the colors fade across the entire shape along a straight line, or radial, where they fade across a radius, and the colors form concentric rings. Less common is the circular gradient, where colors transition around a circle. We’ll look at the first two in this section.

Linear Gradient

A linear or axial gradient “varies along an axis between two defined end points. All points that lie on a line perpendicular to the axis have the same color value.” Let’s look at an example.

- (void)drawGradientFillsInContext:(CGContextRef)context {
	UIGraphicsPushContext(context);
	CGFloat colors[] = { 
        1.0, 1.0, 1.0, 1.0, 
        0.0, 0.5, 1.0, 0.8
    };
	
    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
    CGColorSpaceRelease(baseSpace), baseSpace = NULL;
	
	CGRect rect = CGRectMake(50, 60, 100, 60);
    CGContextSaveGState(context);
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);
	
    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
	
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient), gradient = NULL;
	
    CGContextRestoreGState(context);
	
    CGContextAddEllipseInRect(context, rect);
    CGContextDrawPath(context, kCGPathStroke);
	UIGraphicsPopContext();
}

We begin by defining the colors for our gradient. The colors are passed in as a C-style array of CGFloats consisting of color components. All colors are represented as four float values from 0.0 to 1.0, in the order Red-Green-Blue-Alpha. Here, we create a gradient that transitions from white to a partly-transparent version of the aqua color we saw above. We can create a gradient with more colors simply by adding more numbers to our colors array.

Next, we have to grab a color space, which basically is a representation of the color calibration. This is more useful when displaying the same thing across different color spaces, such as the difference between the screen and a printout. The next line is what we’re interested in—we get a Quartz gradient, of type CGGradientRef, by calling CGGradientCreateWithColorComponents(). This function takes four arguments. The first is the color space you got back. The second is an array of the component colors. This array should have as many items as the product of the fourth argument and the number of components the color space specifies. In this case, that would be 4. The third argument is the relative location of the colors in the gradient. Each CGFloat value must be between 0 and 1, and those values represent the location of the corresponding color in the gradient. For example, if you had four colors and you passed in [0, 0.1, 0.2, 1], the first three colors will be clustered at the start, 10% of the way along the gradient, and 20% of the way along the gradient. The last color would be at the end of the gradient. If you pass in NULL for this argument, as the code above does, the first color is assigned to location 0 (the start of the gradient), the last color is assigned to location 1 (the end of the gradient), and all other colors are equally spaced in between. The final argument is a count of the number of colors.

In our code example, after we create the gradient, we release the color space. Quartz has its own memory management system, because we’re not dealing with regular Objective-C objects.

In the next block of code, we create a rectangle to draw with. We then call CGContextSaveGState(). This is similar to pushing and popping the graphics context, except that each context has its own state of graphics states. By pushing a new graphics state, we constrain our gradient operations to only the shape we’re about to draw. We then draw the ellipse, and call CGContextClip() to clip or constrain the gradient to the outline of the shape.

Next, we set the start and end point of the gradient. This creates a line that the gradient follows; the location of the points determines the angle of the line, and consequently the angle of the gradient. In this case, we’re creating a vertical line down the center of the shape, from the top to the bottom. We then call CGContextDrawLinearGradient(), which takes five arguments. The first is the graphics context. The second is the CGGradient object we created earlier. The next two are the start and end points, and the last one is an integer that determines whether to draw the gradient’s end colors beyond the end points.

Here is another example:

CGFloat rainbowColors[] = {
		1.0, 0.0, 0.0, 1.0,
		1.0, 0.5, 0.0, 1.0,
		1.0, 1.0, 0.0, 1.0,
		0.0, 1.0, 0.0, 1.0,
		0.0, 1.0, 0.5, 1.0,
		0.0, 0.0, 1.0, 1.0,
		1.0, 0.0, 1.0, 1.0
	};
	CGFloat locations[] = {0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.85};
	CGGradientRef rainbow = CGGradientCreateWithColorComponents(baseSpace, rainbowColors, locations, 7);
	// CGColorSpaceRelease(baseSpace), baseSpace = NULL;
	CGRect square = CGRectMake(160, 20, 140, 140);
	CGContextSaveGState(context);
	CGContextAddRect(context, square);
	CGContextClip(context);
	startPoint = CGPointMake(160, 160);
	endPoint = CGPointMake(300, 20);
	CGContextDrawLinearGradient(context, rainbow, startPoint, endPoint, 0);
	CGGradientRelease(rainbow), rainbow = NULL;
	CGContextRestoreGState(context);
	CGContextAddRect(context, square);
	CGContextDrawPath(context, kCGPathStroke);

Here, we draw a diagonal rainbow.

Rainbow Gradient

Rainbow Gradient

Radial Gradient

A radial gradient “is a fill that varies radially along an axis between two defined ends, which typically are both circles. Points share the same color value if they lie on the circumference of a circle whose center point falls on the axis. The radius of the circular sections of the gradient are defined by the radii of the end circles; the radius of each intermediate circle varies linearly from one end to the other.” One of the ends may be a single point rather than a circle (a point is simply a circle with a radius of 0). If one circle is partly or completely outside the other, you will end up with a cone- or cylinder-like shape.

The code for drawing a radial gradient is similar to drawing a linear gradient. You define locations and color components and then create a CGGradientRef with a color space. You then call CGContextDrawRadialGradient() to draw the actual gradient. Let’s see an example:

CGFloat redBallColors[] = {
		1.0, 0.9, 0.9, 0.7,
		1.0, 0.0, 0.0, 0.8
	};
	CGFloat glossLocations[] = {0.05, 0.9};
	CGGradientRef ballGradient = CGGradientCreateWithColorComponents(baseSpace, redBallColors, glossLocations, 2);
	CGRect circleBounds = CGRectMake(20, 250, 100, 100);
	startPoint = CGPointMake(50, 270);
	endPoint = CGPointMake(70, 300);
	CGContextDrawRadialGradient(context, ballGradient, startPoint, 0, endPoint, 50, 0);
	CGContextAddEllipseInRect(context, circleBounds);
	CGContextDrawPath(context, kCGPathStroke);

This code will draw a glossy red ball:

Glossy Red Ball

Glossy Red Ball

In this code, we define the colors and gradient just as before. However, when drawing a radial gradient we don’t need to clip to a shape, unless we wanted to; in this case, we’re drawing a ball, so the default circular shape is fine for our needs. CGContextDrawRadialGradient() takes 7 arguments. The first two are the context and the gradient, same as before. The next two are the start point and the radius of the first circle—we’ll play with that next. The next two are the end point and the radius of the second circle; we set this at 50 to create a ball with a size of 100×100. The last argument is an integer specifying whether to draw beyond the bounds.

This example will draw a radial gradient background, clipped in a rectangle:

CGFloat backgroundColors[] = {
		0.3, 0.3, 0.3, 1.0,
		0.1, 0.1, 0.1, 1.0
	};
	CGGradientRef backgroundGradient = CGGradientCreateWithColorComponents(baseSpace, backgroundColors, NULL, 2);
	CGContextSaveGState(context);
	CGRect backgroundRect = CGRectMake(20, 150, 80, 50);
	CGContextAddRect(context, backgroundRect);
	CGContextClip(context);
	startPoint = CGPointMake(CGRectGetMidX(backgroundRect), CGRectGetMidY(backgroundRect));
	CGContextDrawRadialGradient(context, backgroundGradient, startPoint, 0, startPoint, 35, kCGGradientDrawsAfterEndLocation);
	CGContextRestoreGState(context);
	CGContextAddRect(context, backgroundRect);
	CGContextDrawPath(context, kCGPathStroke);

Here, we see a radial gradient constrained in a rectangle. The gradient’s radius doesn’t take it all the way to the edge of the rectangle, so the rest of the rectangle is filled with the end color. This is specified by the kCGGradientDrawsAfterEndLocation parameter passed to CGContextDrawRadialGradient().

Let’s look at one last example:

[[UIColor colorWithRed:0 green:0.5 blue:0 alpha:0.5] setStroke];
	CGContextAddEllipseInRect(context, CGRectMake(180, 180, 100, 100));
	CGContextDrawPath(context, kCGPathStroke);
	CGFloat coneColors[] = {
		0.2, 0.8, 0.2, 1.0,
		1.0, 1.0, 0.9, 0.9
	};
	CGGradientRef coneGradient = CGGradientCreateWithColorComponents(baseSpace, coneColors, NULL, 2);
	startPoint = CGPointMake(230, 230);
	endPoint = CGPointMake(280, 330);
	CGContextDrawRadialGradient(context, coneGradient, startPoint, 50, endPoint, 10, 0);
	CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.1 green:0.6 blue:0.1 alpha:0.3].CGColor);
	CGContextAddEllipseInRect(context, CGRectMake(270, 320, 20, 20));
	CGContextDrawPath(context, kCGPathStroke);
Quartz Cone

Quartz Cone

Because the circles are partly outside of each other, Quartz draws a cone figure.

Image and Pattern Fills

To make more complicated designs, sometimes it’s easier to use a pre-rendered image as a fill. You may also want to repeat (tile) it to fit the area, rather than stretching it and loosing quality.

We start by loading an image into a shape, and by clipping to the shape we can use it as a fill:

CGRect ellipseRect = CGRectMake(20, 30, 100, 80);
	CGContextSaveGState(context);
	CGContextAddEllipseInRect(context, ellipseRect);
	CGContextClip(context);
	[[UIImage imageNamed:@"Image Fill.jpg"] drawInRect:ellipseRect];
	CGContextRestoreGState(context);
	CGContextAddEllipseInRect(context, ellipseRect);
	CGContextDrawPath(context, kCGPathStroke);

This code is mostly old stuff. We have to clip to a shape to constrain the image to that shape; otherwise the whole image would be drawn in the entire rect. Larger images would in fact be drawn at full size, and could cover the whole screen and go beyond. We can draw the image using a method built into UIImage. -drawInRect: takes a CGRect as its only parameter, and draws into that rectangle, filling it unless a clipping path has been defined. There is a similar way to tile images:

CGRect tileRect = CGRectMake(150, 40, 150, 110);
	CGContextSaveGState(context);
	CGContextAddEllipseInRect(context, tileRect);
	CGContextClip(context);		// Clip; otherwise whole rect will be drawn
	[[UIImage imageNamed:@"TileImage.png"] drawAsPatternInRect:tileRect];
	CGContextRestoreGState(context);
	CGContextAddEllipseInRect(context, tileRect);
	CGContextDrawPath(context, kCGPathStroke);

This code should be self-explanatory. The results:

Quartz Pattern and Image  Fills

Quartz Pattern and Image Fills

In the next section, we’ll look at more advanced things we can do with Quartz and related frameworks, including Core Animation.

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";
	else
		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);
	}
	else
		return;
}

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.

UITableViewControllers

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";
			break;
		case 1:
			return @"Images & Fills";
			break;
		case 2:
			return @"Animations";
			break;
		default:
			return nil;
			break;
	}
}

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.

Advertisements
  • 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 223 other followers

  • Back to the Past

    November 2017
    S M T W T F S
    « Apr    
     1234
    567891011
    12131415161718
    19202122232425
    2627282930  
  • Time Machine

  • You count!

    • 620,617 views
  • Worldwide Stats

    free counters
%d bloggers like this: