STEP #6: Enhance Your Simple Table App With Property List
by Simon Ng
However, it’s not a good practice to “hard code” every item in the code. In real app, we used to externalized these static items (i.e. the recipe information) and put them in a file or database or somewhere else. In iOS programming, there is a type of file called Property List.
This kind of file is commonly found in Mac OS and iOS, and is used for storing simple structured data (e.g. application setting). In this tutorial, we’ll make some changes in our simple table app and tweak it to use Property List.
In brief, here are a couple of stuffs we’ll cover:
- Convert table data from static array to property list
- How to read property list
Why Externalize the Table Data?
It’s a good practice to separate static data from the code. But why? What’s the advantage to put the table data into an external source. Let’s ask you to add 50 more recipes in our simple table app. Probably, you’ll go back to your code and put all the new recipes in the initialization:
1
2 3 4 5 6 7 8 |
// Initialize table data
tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil]; // Initialize thumbnails thumbnails = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"mushroom_risotto.jpg", @"full_breakfast.jpg", @"hamburger.jpg", @"ham_and_egg_sandwich.jpg", @"creme_brelee.jpg", @"white_chocolate_donut.jpg", @"starbucks_coffee.jpg", @"vegetable_curry.jpg", @"instant_noodle_with_egg.jpg", @"noodle_with_bbq_pork.jpg", @"japanese_noodle_with_pork.jpg", @"green_tea.jpg", @"thai_shrimp_cake.jpg", @"angry_birds_cake.jpg", @"ham_and_cheese_panini.jpg", nil]; // Initialize Preparation Time prepTime = [NSArray arrayWithObjects:@"30 min", @"30 min", @"20 min", @"30 min", @"10 min", @"1 hour", @"45 min", @"5 min", @"30 min", @"8 min", @"20 min", @"20 min", @"5 min", @"1.5 hour", @"4 hours", @"10 min", nil]; |
There is nothing wrong doing this. But look at the code! It’s not easy to edit and you have to strictly follow the Objective C syntax. Changing the code may accidentally introduce other errors. That’s not we want. Apparently, it would be better to separate the data and the programming logic (i.e. the code). Does it look better when the table data is stored like this?
Sample Property List
In reality, you may not be the one who provides the table data (here, the recipe information). The information may be given by others without iOS programming experience. When we put the data in an external file, it’s easier to read/edit and more understandable.
As you progress, you’ll learn how to put the data in server side (or what-so-called the Cloud). All data in your app are pulled from the server side on demand. It offers one big benefit. For now, any change of the data will require you to build the app and submit it for Apple’s approval. By separating the data and put them in the Cloud, you can change the data anytime without updating your app.
We’re not going to talk about the Cloud for today. Let’s go back to the basic and see how you can put all the recipes in a Property List.
What is Property List
Property list offers a convenient way to store simple structural data. It usually appears in XML format. If you’ve edited some configuration files in Mac or iPhone before, you may come across files with .plist extension. They are examples of the Property List.You can’t use property list to save all types of data. The items of data in a property list are of a limited number of types including “array”, “dictionary”, “string”, etc. For details of the supported types, you can refer to the Property List documentation.
Property list is commonly used in iOS app for saving application settings. It doesn’t mean you can’t use it for other purposes. But it is designed for storing small amount of data.
Is it the Best Way to Store Table Data?
No, definitely not. We use property list to demonstrate how to store table data in an external file. It’s just an example. As you gain more experience, you’ll learn other ways to store the data.Convert Table Data to Property List
That’s enough for the background. Let’s get our hands dirty and convert the data into a property list. First, open the Simple Table project in Xcode. Right click on the “SimpleTable” folder and select “New File…”. Select “Other” under “iOS” template, choose “Property List” and click “Next” to continue.
Create a New Property List File
Empty Property List
Add a New Row in Property List Editor
Define Three Arrays in Property List
Step by Step Procedures to Add an Item in Array
Recipe Property List
As mentioned earlier, the property list is usually saved in the format of XML. To view the source of the property list, right click and select “Open as Source Code”.
View the Source Code of Property List
Source Code of Recipes.plist
Loading Property List in Objective C
Next, we’ll change our code and load the recipe from the property list we just built. It’s fairly easy to read the content of property list. The iOS SDK already comes with some built-in functions to handle the read/write of the file.Replace the following code:
1
2 3 4 5 6 7 8 |
// Initialize table data
tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil]; // Initialize thumbnails thumbnails = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"mushroom_risotto.jpg", @"full_breakfast.jpg", @"hamburger.jpg", @"ham_and_egg_sandwich.jpg", @"creme_brelee.jpg", @"white_chocolate_donut.jpg", @"starbucks_coffee.jpg", @"vegetable_curry.jpg", @"instant_noodle_with_egg.jpg", @"noodle_with_bbq_pork.jpg", @"japanese_noodle_with_pork.jpg", @"green_tea.jpg", @"thai_shrimp_cake.jpg", @"angry_birds_cake.jpg", @"ham_and_cheese_panini.jpg", nil]; // Initialize Preparation Time prepTime = [NSArray arrayWithObjects:@"30 min", @"30 min", @"20 min", @"30 min", @"10 min", @"1 hour", @"45 min", @"5 min", @"30 min", @"8 min", @"20 min", @"20 min", @"5 min", @"1.5 hour", @"4 hours", @"10 min", nil]; |
with:
1
2 3 4 5 6 7 8 |
// Find out the path of recipes.plist
NSString *path = [[NSBundle mainBundle] pathForResource:@"recipes" ofType:@"plist"]; // Load the file content and read the data into arrays NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path]; tableData = [dict objectForKey:@"RecipeName"]; thumbnails = [dict objectForKey:@"Thumbnail"]; prepTime = [dict objectForKey:@"PrepTime"]; |
Behind the Code Change
Line #2 – Before reading the “recipes.plist” file, you have to first retrieve the full path of the resource.Line #5 – You have defined three keys (RecipeName, Thumbnail, PrepTime) in the property list. In the example, each key is associated with a specific array, which is the value. In iOS programming, we use the term dictionary to refer to this key-value pair association. NSDictionary class provides the necessary methods for managing the dictionary. Here, we use the “initWithContentsOfFile” method of NSDictionary class to read the key-value pairs in a property list file.
Line #6-8 – These lines of code retrieves the corresponding array with the key we defined earlier.
STEP #5: How To Handle Row Selection in UITableView
First, let’s revisit our app and see what we’ll add to it.
- Display an alert message when user taps a row
- Display a check mark when user selects a row
Understanding UITableViewDelegate
When you first built the Simple Table View app, you’ve declared two delegates (UITableViewDelegate, UITableViewDataSource) in the SimpleTableController.h:
1
2 3 4 5 |
#import <UIKit/UIKit.h>
@interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> @end |
It’s very common to come across various delegates in iOS programming. Each delegate is responsible for a specific role or task to keep the system simple and clean. Whenever an object needs to perform certain task, it depends on another object to handle it. This is usually known as separation of concern in system design.
When you look at the UITableView class, it also applies this design concept. The two delegates are catered for different purpose. The UITableViewDataSource delegate, that we’ve implemented, defines methods that are used for displaying table data. On the other hand, the UITableViewDelegate deals with the appearance of the UITableView, as well as, handles the row selection.
It’s obvious we’ll make use of the UITableViewDelegate and implement the required method for handling row selection.
Handling Table Row Selection
Before we change the code, you may wonder:How do we know which methods in UITableViewDelegate need to implement?
You can always refer to the Apple’s iOS programming reference. There are two ways to access the documentation. You can access the API document on Apple’s website. Or simply look it up inside Xcode. For example, you can bring up the API document of UITableViewDelegate, just place the cursor over the class name and press “control-command-?”. You’ll see the following popup:
Shortcut to Access API Doc
UITableViewDelegate Protocol Reference
– tableView:willSelectRowAtIndexPath:
– tableView:didSelectRowAtIndexPath:
Both of the methods are used for row selection. The only difference is that “willSelectRowAtIndexPath” is called when a specified row is about to be selected. Usually you make use of this method to prevent selection of a particular cell from taking place. Typically, you use “didSelectRowAtIndexPath” method, which is invoked after user selects a row, to handle the row selection and this is where you add code to specify the action when the row is selected. In this tutorial, we’ll add a couple of actions to handle row selection:
- Display an alert message
- Display a check mark to indicate the row is selected
Let’s Code
Okay, that’s enough for the explanation. Let’s move onto the interesting part – code, code, code!In Xcode, open the “SimpleTableViewController.m” and add the following method before “@end”.
1
2 3 4 5 6 7 8 9 |
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ UIAlertView *messageAlert = [[UIAlertView alloc] initWithTitle:@"Row Selected" message:@"You've selected a row" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; // Display Alert Message [messageAlert show]; } |
When a row is selected, an alert message is displayed
Your Exercise
For now, we just display a generic message when a row is selected. It’s always better to display an informational message like below:
Default Structure of a UITableViewCell
- Image – the left part is reserved for displaying thumbnail just like what we’ve done in the Simple Table App tutorial
- Content – the main part is used for displaying text label and detailed text
- Accessory view – the right part is reserved for accessory view. There are three types of default accessory view including disclosure indicator, detail disclosure button and check mark. The below figure shows you how these indicators look like.
UITableViewCell Accessory View
1
2 |
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark; |
Compile and run the app. After you tap a row, it’ll show you a check mark.
1
|
[tableView deselectRowAtIndexPath:indexPath animated:YES];
|
What’s Upcoming Next?
What do you think about the series of Table View tutorials? I hope you’ve learnt a ton! By now, you should have a better understanding about how to create table view, customize table cells and handle table row selection. Make sure you understand the information presented in the tutorials as UITableView is one of the common UI elements in iOS. If you have any questions, head to our forum and share with us.There are still lots of stuffs to learn in iOS programming. In coming tutorials, we’ll see how you can replace the recipe array with a file and explore Navigation Controller, as well as, Storyboard to build a more complex application.
Update: You can now download the full source code of the Xcode project.
You May Like These:
Understanding XML and JSON Parsing in iOS Programming
Working with CloudKit in iOS 8
Beginner's Guide: Using Social Framework and UIActivityViewController
Filed Under: Course, Tutorials Tagged With: iOS Programming, iOS SDK, iOS Tutorial, UITableView, UITableViewCell
Get Free Chapters of Our Swift Book
Sign Up for our Free Tutorials
- Learn iOS Programming From Scratch
- Step by Step Guide to Build Your First iPhone App
- Complete Source Code for Your Reference
- More Programming Tips and Tutorials to Come
Whatcha waiting for?
Subscribe to:
Comments (Atom)
Popular Posts
-
Update: This tutorial only works for Xcode 4.6 or lower. If you’ve upgraded to Xcode 5, please check out the updated Hello World tutorial. ...
-
If you’ve followed the iOS programming tutorials , I believe you should manage to create a simple Table View app with custom tab...
-
1. Get a Mac Yes, you need a Mac. It’s the basic requirement for iOS development. To develop an iPhone (or iPad) app, you need to first...
