iOS: Table View using Property List

Table Views are the most common object used to display lists of data to the user. This objects are highly configurable, they can be made to look different things. Mail, Contacts, and Messages to name a few apps using the Table View. Mail uses table view to display lists of accounts, folders, and messages, but table views are not limited to display text, they are also used in YouTube, Settings, and other applications, even though this applications has many different appearances. Property list files use the filename extension .plist, and thus are often referred to as plist files. Property lists organize data into named values and lists of values using several object types. These types give you the means to produce data that is meaningfully structured, transportable, storable, and accessible, but still as efficient as possible. Property lists are frequently used by applications running on both Mac OS X and iOS. The property-list programming interfaces for Cocoa and Core Foundation allow you to convert hierarchically structured combinations of these basic types of objects to and from standard XML. You can save the XML data to disk and later use it to reconstruct the original objects. Note: To know more about property list, go here: http://developer.apple.com/library/mac /#documentation/cocoa/conceptual/PropertyLists/Introduction/Introduction.html Note: Table views can have as many rows as you want, only constrained by the amount of available memory.

Table Views and Table View Cells

A table view is the object that displays data in a table manner and it’s an instance of the class UITableView. Each visible rows are implemented by table view cell and it’s an instance of the class UITableViewCell.
iOS: Table View using Property List - Table View diagram
Table views are not responsible for storing data, they store only enough data to draw the rows on the currently visible cells. Tables have a single column with multiple rows. They can scroll vertically and display large data sets.

UITableView

The UITableView class represents the table view. This class is for displaying and editing information lists. UITableView classes have an associated UITableViewController, UITableViewDelegate, and a UITableViewDataSource.
UITableViewController
The UITableViewController class creates a controller object that manages a table view. It implements the following behavior:
  • If a nib file is specified via the initWithNibName:bundle: method (which is declared by the superclass UIViewController), UITableViewController loads the table view archived in the nib file. Otherwise, it creates an unconfigured UITableView object with the correct dimensions and autoresize mask. You can access this view through the tableView property.
  • If a nib file containing the table view is loaded, the data source and delegate become those objects defined in the nib file (if any). If no nib file is specified or if the nib file defines no data source or delegate, UITableViewController sets the data source and the delegate of the table view to self.
  • When the table view is about to appear the first time it’s loaded, the table-view controller reloads the table view’s data. It also clears its selection (with or without animation, depending on the request) every time the table view is displayed. The UITableViewController class implements this in the superclass method viewWillAppear:. You can disable this behavior by changing the value in the clearsSelectionOnViewWillAppear property.
  • When the table view has appeared, the controller flashes the table view’s scroll indicators. The UITableViewController class implements this in the superclass method viewDidAppear:.
  • It implements the superclass method setEditing:animated: so that if a user taps an Edit|Done button in the navigation bar, the controller toggles the edit mode of the table.
UITableViewDelegate and UITableViewDataSource
UITableViewDelegate and UITableViewDataSource are protocols at least one class in your application must adopt if your application contains a UITableView. You can create your own custom classes to adopt these protocols, or create a UITableViewController that will automatically adopt these protocols. In this case, we did use a UITableViewController so these 2 protocols are adopted automatically not needing to type extra codes. Note: UITableViewDataSource provides the table with data while the UITableViewDelegate provides the other tasks. Note: To know more about UITableViewController class, go here: UITableView Class Reference As mentioned above, table views has single column, but if you will look at the YouTube application, does have the appearance of 3 columns.
iOS: Table View using Property List - Youtube App
But no, each row in the table view is represented by a single column, and this column is represented by a single UITableViewCell. Each cell can be configured with an image, text and accessory icons, which is the small icons on the right.
UITableViewStyle: Plain and Grouped
Table view comes in with two basic styles: Plain and Grouped. You can change the table view’s style by using the code UITableViewStylePlain and UITableViewStyleGrouped. The plain style is the default style, when an index is used, this style is also referred to as indexed.
iOS: Table View using Property List - Table View Style
Note: I will not tackle the indexed table. I will focus on the main subject, basic data using a Property List file and basic table view that will display the array of data from the file.

Creating a simple Application

Let’s create a simple, and I mean the simplest possible way to create and implement a table view to see how it works. Create a new Xcode project. For this tutorial, we will use the navigation-based application on the menu.
Coding the App
First, we should create an NSArray object to handle the data from the plist. Your @interface should look like this:
@interface RootViewController : UITableViewController

@property (nonatomic, retain) NSArray *ToDoList;

@end
That’s it! The interface for our simple app is complete. Next will be to synthesize the object we created:
@synthesize ToDoList;
After synthesizing the object, you should always release them in the - dealloc method and nil it out in the - viewDidUnload method if it is a view object (e.g. UILabel, UIButton). Note: It is a good practice to write the code to release or nil out an object right after you synthesize the object. By doing so, you won’t forget to release or nil them out and avoid unnecessary memory leaks due to unreleased objects. Tip: Putting the -dealloc method right after the -init or the -didReceiveMemoryWarning and the -viewDidUnload method right after the -viewDidLoad method is a great practice. This way you won’t forget to release the object. We will now create 2 objects inside the - viewDidLoad method, these objects will handle the data from the plist file and will then transfer the data to the toDoList property.
NSString *bundle = [[NSBundle mainBundle] pathForResource: @"ToDoList" ofType: @"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile: bundle];
[self setToDoList: array];
When the view did load, an NSString object called bundle will be created containing the path of the ToDoList.plist (download link at the bottom). We’ll then create an NSArray object to contain the data from the plist file. We will use the method - arrayWithContentsOfFile to get the array data from a file with the path stored to the bundle object. Your - viewDidLoad method should look like this:
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *bundle = [[NSBundle mainBundle] pathForResource: @"ToDoList" ofType: @"plist"];
    NSArray *array = [NSArray arrayWithContentsOfFile: bundle];
    [self setToDoList: array];
}
We’re done creating and implementing the data, next is to setup the table view. First you need to implement the required data source and delegate methods of the UITableViewController. Note: Common practice is to make the view controller conforms to the UITableView data source and delegate, but this time our view controller is a subclass of the UITableViewController so it is not needed. The methods we need are: – tableView:cellForRowAtIndexPath: – numberOfSectionsInTableView: – tableView:numberOfRowsInSection: The first method will return a UITableViewCell (this is a required data source method), the second method will return how many number a section will have, and the last method will show the number of rows a section will have (this is a required data source method). We will only need 1 section for this project so we will only return 1. The code should look like this:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
Then we will need rows the same amount the toDoList array object has. We can get the amount the array has by calling the method - count.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [toDoList count];
}
After setting the number of row and section, we will now need to setup the cell for the row by calling the last method. We will set the cell’s text from the string inside the array.
[[cell textLabel] setText: [toDoList objectAtIndex: [indexPath row]]];
This piece of code will get the corresponding data for the row inside the array by using the indexPath. Of course, before this we should create an identifier for the cell and a cell. Inside the method – tableView:cellForRowAtIndexPath::
static NSString *CellIdentifier = @"Cell";
    
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
Static means that you will allocate the object statically. Note: To know more about static variables, go here: http://en.wikipedia.org/wiki/Static_variable The 3rd line creates a cell object from a reusable cell. If the cell is nil then it creates and allocates a new cell, if not, then it will use the cell again so long as the identifier are the same. The complete code of – tableView:cellForRowAtIndexPath: should look like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    [[cell textLabel] setText: [toDoList objectAtIndex: [indexPath row]]];
    
    return cell;
}
The app is now complete. Run the app to open the app in the simulator. It should look like this:
iOS: Table View using Property - Final App

Conclusion

In this tutorial, we created a table view using the data of a plist file. We learned how to use a UITableViewController and Property List file and understand the basic of table view. Note: There are many more methods and properties you can use to customize a table cell’s behavior and appearance than presented in this tutorial. For more information, refer to the online class references for each of the classes covered in this chapter and also reference Apple’s Table View Programming Guide for iOS.