How to Add Sections to a Table View in Your iOS App

By Neal Goldstein, Dave Wilson

For your iOS app, you may need to add sections to a table view. In a grouped Table view, each group is referred to as a section. The two methods you need to implement to start things off are as follows:

numberOfSectionsInTableView:(UITableView *)tableViewtableView:(UITableView *)tableView     numberOfRowsInSection:(NSInteger)section

Each of these methods returns an integer, and that integer tells the Table view something — the number of sections and the number of rows in a given section, respectively.

Add these methods to DestinationController.m to create a Table view that has one section with the number of rows equal to the number of destinations you have in your Destinations.plist. You will get compiler errors that you will fix with code in the next Listing.

- (NSInteger)numberOfSectionsInTableView:
(UITableView *)tableView {
return 1;
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
NSString *filePath = [[NSBundle mainBundle]
pathForResource:@"Destinations" ofType:@"plist"];
NSDictionary *destinations =
[NSDictionary dictionaryWithContentsOfFile: filePath];
self.destinationsArray = destinations[@"DestinationData"];
return [destinationsArray count];

The numberOfSectionsInTableView: method is obvious. In the tableView:numberOfRowsInSection: method, you access Destination.plist to extract what you need. In this case, it’s the DestinationData array, which, to refresh your memory, is an array of dictionaries that have the data for each destination and return the count.

Keep in mind that the first section is zero, as is the first row. This means, of course, that whenever you want to use an index to get to the first row or section, you need to use 0, not 1 — and an index of 1 for the second row and so on.

You’ll get an Xcode Live Issue error here because you need to add the new destinationArray property. In addition, remember that you declared the selectedDestinations property in DestinationController.h as readonly. That is fine for the public interface, but you need to be able to set it from within DestinationController.m.

You can do that by overriding the public property. (This is a very common pattern for a property — to the public readonly but readwrite within the implementation of the class that declares it.)

To do those things, add the bolded code in Listing 20-5 to DestinatoinController.m.

#import "DestinationController.h"
@interface DestinationController ()
@property (strong, nonatomic)
NSArray *destinationsArray;
@property (nonatomic, readwrite)
NSUInteger selectedDestination;